In a project that I was working on, I was required to convert a string into a integer. I got this problem were whatever I input it will not accept as valid input.
Here is the problem code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
do
{
ss.flush();
ss.clear();
std::cout<< "Please type in your employees hours they worked for the first day:\n";
std::getline (std::cin, temp);
ss<< temp;
ss>> E.hours;
if (!ss.good())
{
std::cout<< "You have typed in something that is not a integer,\n""or you did and put stuff after it.\n";
}
} while(!ss.good());
#include <iostream>
#include <sstream>
#include <string>
usingnamespace std;
int main ()
{
string UserInput;
int FinalVal;
cout << "Please enter a number." << endl;
while (true)
{
getline (cin , UserInput);
UserInput.erase (UserInput.find_last_not_of (" \t") + 1);
istringstream MyStream (UserInput);
MyStream >> FinalVal;
if (MyStream.eof ())
{
break;
}
cout << "The value you entered was not a number." << endl;
}
cout << "Okay you entered a number and it was " << FinalVal << endl;
cout << "Press ENTER to end the program." << endl;
cin.get ();
return 0;
}
That is now this:
By the way thanks Duoas for the great post
Please enter a number.
Number
The value you entered was not a number.
4
Okay you entered a number and it was 4
Press ENTER to end the program.
void create_employees (std::vector<employee>& employees)
{
employee E;
std::string temp;
std::stringstream ss;
std::string answer = "yes";
E.id = 0;
...
do
{
ss.flush();
ss.clear();
std::cout<< "Please type in your employees hours they worked for the first day:\n";
std::getline (std::cin, temp);
temp.erase (temp.find_last_not_of (" \t") + 1);
ss<< temp;
ss>> E.hours;
if (!ss.eof())
{
std::cout<< "You didn't type a number or you did and put something after it.\n";
}
} while(!ss.eof());
And I found that when I type a number the first time it works. But if i type argle then a number then it doesn't work. Can anybody tell me what is going on here?
Yes, you are abusing the stringstream... they weren't really designed to be able to handle reuse that way. Instead, create a new one in each iteration of the loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
while (true)
{
std::cout << "Please type in ...";
string s;
std::getline (std::cin, s);
s.erase (s.find_last_not_of (" \t") + 1);
istringstream ss (s);
ss >> E.hours;
if (ss.eof()) break; // only escape on valid input!
std::cout << "Try again...";
}