Guess I'm overcomplicating it but want to be sure. |
Well, your code looks a bit complicated, but it’s not your fault :-)
This problem (of the trailing ‘\n’ in input instructions) is one of most most common requests for help on this forum, and I’m afraid it doesn’t have a simple answer. Every solution I’ve read so far requires quite a few lines of code.
In my (totally personal an perhaps not shared) opinion, the best way to solve this problem is by eliminating the trailing ‘\n’ from the input buffer from the very beginning. This can be done by the function std::getline(), as Ihatov proposed, which reads an entire line (spaces included) and discards the final ‘\n’:
http://en.cppreference.com/w/cpp/string/basic_string/getline
But once you have used std::getline(), you’ve got your input inside a std::string, not a number variable:
1 2 3 4
|
std::cout << "Please give me a number: ";
std::string line;
std::getline(std::cin, line);
// the user input is now stored inside the std::string line
|
It means you can’t yet use it as a number.
Then you need to get if out of the string and store it into a number - and again you need to choose between different methods. The most used is creating an instance of an object called stringstream and passing the std::string to its constuctor:
std::stringstream ss(line);
http://en.cppreference.com/w/cpp/io/basic_stringstream
Now you can use that std::stringstream as you would use std::cin:
1 2 3
|
double mydouble = 0.0;
int myint = 0;
ss >> mynum >> myint;
|
It looks very complicated, but you’ve succeeded in getting rid of the trailing ‘\n’ :-)
Alternatively, you can use std::atoi() or std::atof() on the std::string (or std::strtol, as suggested by Ihatov):
http://en.cppreference.com/w/cpp/header/cstdlib
std::atoi(line.c_str());
or even std::stoi(), std::stod():
http://en.cppreference.com/w/cpp/string/basic_string/stol
std::stoi(line);
(but you need to know how to deal with exceptions, in this last case).
The other methods, in my opinion, are even more complicated.
Happy coding!