简体   繁体   中英

Convert string of dynamic size to ints with stringstream

I'm trying to add int values to a vector, by converting a user-given string with stringstream. The user gives the data like this: 1,5,6,7,4 so I'll never know exactlyhow many int there will be.

Right now I only get the first entered numbers. The rest is ignored. This is what I kind of want:

stringstream ss;
int tmpInt;
string data;

cout << "Enter data: (1,2,3,4 etc.)";
getline(cin, data);

ss.str(data);

while(ss >> tmpInt)
{
    myList.addValue(tmpInt);
}

You need to make sure you ignore the commas:

while(ss >> tmpInt)
{
    myList.addValue(tmpInt);
    ss.ignore();
}

Currently, the extraction will attempt to read an integer, find that there's a comma, and stick the stream in a failed state.

Alternatively, if you want to check whether the character is actually a comma (for the sake of input validation), you could do:

while(ss >> tmpInt)
{
    myList.addValue(tmpInt);
    if (ss.get() != ',') break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM