-2

I have a problem - I want to store values from standard input line to an int but am unsure how to convert to an int:

string line;
int value;
getline(cin,line);
istringstream ss(line);
while (ss>>line) {
    if (ss.eof()==false) {
        // stores non ints in strings
    }
    else {
        value=line; //ERROR
    }
}

I have tried to convert this using standard documentation material but I am going nowhere. What am I doing wrong?

theBookeyMan
  • 37
  • 1
  • 3
  • 9

2 Answers2

0

You can use std::stoi:

value=std::stoi(line);
yizzlez
  • 8,757
  • 4
  • 29
  • 44
  • Thanks. I tried that and I'm getting error: 'stoi' is not a member of 'std'. I have included the right libraries eg. std::stoi so is this not a library problem? – theBookeyMan Jul 28 '15 at 14:32
  • @theBookeyMan Did you include , are you using c++11? – yizzlez Jul 28 '15 at 14:33
0

You could use your istringstream to try loading a value into an int while checking for ss.fail().

ss >> temp; // where temp is an int
if(ss.fail())
{
// handle the error because the value wasn't an int
}
else
{
// process your int
}

This, naturally, could be modified a bit based on your needs.

Tyler
  • 197
  • 3
  • 13