1

In the process of expanding my knowledge of c++ outside of using an arduino. I am starting with the basics and expanding outward. Below is a program I wrote to take a users name and age. Ideally if the user enters the age correctly, it will print out the value at the end.

However if the user inputs a letter than it will tell them no and ask for a correct age.

Probably not the best logic but I found that characters input into an int turn into 0 and as one can't have an age of 0, I have an if checking for the input and making sure it is not 0.

So for some reason it doesn't work properly: The age variable is always zero. I suspect it might be I'm using an int for the age instead of a double but ...

#include "pch.h"
#include <iostream>
#include <string>

int num1, num2;
std::string Usrname;


int main()
{
    std::cout << "Name: ";
    getline(std::cin, Usrname);
    num1 = Usrname.length();

    int ok = 0;
    while (ok == 0) {
        std::cout << "Age: ";
        std::cin.get() >> num2;
        std::cin.ignore();
        if (num2 == 0) {
            std::cout << "Wrong Input, Please input ";
        }
        else { ok = 1; }
    }
    std::cout << "The Name " << Usrname << " is " << num1 << " Characters long." << std::endl;
    std::cout << Usrname << " is " << num2 << " years old." << std::endl;

    return 0;
}
Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
Hojo.Timberwolf
  • 985
  • 1
  • 11
  • 32
  • *"for some reason it doesn't work properly"* Are you getting compiler error(s)? If so, post them as well. – CinCout Mar 29 '19 at 05:54
  • 1
    You can't determine that reading failed by examining the value – how would you tell the difference between reading 0 and failure? (In your code, `num2` is initialised to zero, so you can't tell if failing to read did anything.) Get yourself a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Mar 29 '19 at 06:06

1 Answers1

3
std::cin.get() >> num2;

should be

std::cin >> num2;

P.S. The correct way to learn C++ includes learning the proper use of your debugger, especially the boring step by step execution.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
  • This does fix the problem with the numerical inputs, however it leads into another problem which is an infinite loop when the input is wrong. I will expand the question. – Hojo.Timberwolf Mar 29 '19 at 06:24