How do I let the user to input integer and character separated by comma?
"example: 1,2,-1,a,b". I used the following code but my switch statement is not working with -1.
cin will get only till first space you may want to use getline there but you dont want to getline with delimiter as "," read line till newline (which is default) from standard input of file), then use the string stream to parse through the read line with "," as delimiter.
Also, single quote is used for delimiting a single character, '-1' would mean you are trying to enclose two characters in single quotation marks. Since you will be dealing with strings you have to compare two strings.
Little Bobby Tables the code looks so complicated for me. Codewalker i don't understand what you said. I changed cin to getline(cin,input). But now it does not wait for me to input. And with comparision i used a if statement before switch its not working either. Is there a easy way to do this?
Your original code was along the right lines, except for one thing. You can't use switch-case with a character string. If you changed it to a series of if and else if statements it should be ok.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
string input;
getline(cin, input);
istringstream ss(input);
string token;
while (getline(ss,token,','))
{
if (token == "-1")
{
//code
}
elseif (token == "a")
{
// etc.
}
// etc.
}
Depending on the type of input which is to be acceptable, you may want to add additional processing, for example another stringstream to extract integers from the token, or maybe remove all spaces from the input string before entering the while loop perhaps.
I changed cin to getline(cin,input). But now it does not wait for me to input.
Most likely your code has a previous cin >> something; which will have left a trailing newline character in the input buffer. You can clear that if required by using cin.ignore() after that previous cin >>, or cin.ignore(1000, '\n') to get rid of up to 1000 characters, or until a newline is found.
Thanks Chervil now I know what was causing the problem it was the switch statement. I can use "-1" as input now. I tried using getline but it did not work . Like you said i used cin.ignore(1000,'\n') and getlines started working. But code also works using cin .