Reputation: 1091
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;
}
Upvotes: 1
Views: 58
Reputation: 11158
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.
Upvotes: 3