0

I need to write a program that asks the user to enter 3 integers seperated by a comma and a space.

Here's what I've tried:

//start program
//Prompt user to enter 3 numbers.


//obtain input marks as string
getline(cin, snum1, ',');
getline(cin, snum2, ',');
getline(cin, snum3);

//convert marks from string to integer
num1 = stoi(snum1);
num2 = stoi(snum2);
num3 = stoi(snum3);

I've tried both atoi and stoi,

1) stoi gives me an error saying: 'stoi' was not declared in this scope, which from what I have read on similar questions is because my compiler doesn't support C++11, which doesn't help me because I'm using the same compiler my teachers will use when I hand in my assignment, and if the code doesn't compile I get 0%.

2) atoi gives me an error saying: cannot convert 'std::string {aka std::basic_string}' to 'const char*' for argument '1' to 'int atoi(const char*)'.

I've searched this second error and all I've found is complicated solutions that I don't understand or don't work.

Is there no simple way of just getting this input into my variables as integers?

All hints much appreciated.

EDIT:

How is this a duplicate of splitting strings? That thread doesn't help.

  • 2
    add .c_str() to snum1/2/3 when using atoi – user2475983 Aug 24 '15 at 12:32
  • You might want to check out [stringstream](http://www.cplusplus.com/reference/sstream/stringstream/). If you're familiar with Java, it's much like a `parse*` method. `stringstream` actually doesn't care about whitespace, so you really only need to worry about capturing commas and other numerical types if you please. – erip Aug 24 '15 at 12:37
  • @erip You don't need 3 different `char`'s for the commas. you can reuse 1 for all three. Also I would suggest you run the code somewhere like [ideone](https://ideone.com/) so you can just link to the code. – NathanOliver Aug 24 '15 at 12:42
  • @NathanOliver Good idea. I'll put it in ideone and we can clean up the comments. – erip Aug 24 '15 at 12:43
  • https://ideone.com/v7HK2r – erip Aug 24 '15 at 13:40
  • No problem! Keep in mind that you should take advantage of the features of C++ as much as possible. Avoid `c style strings` like the plague -- they're exactly that. – erip Aug 24 '15 at 13:46

0 Answers0