简体   繁体   English

使用stringstream将动态大小的字符串转换为int

[英]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. 我正在尝试通过使用stringstream转换用户提供的字符串来将int值添加到向量中。 The user gives the data like this: 1,5,6,7,4 so I'll never know exactlyhow many int there will be. 用户给出的数据是这样的:1,5,6,7,4,所以我永远不会确切知道会有多少个int。

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: 您需要确保ignore逗号:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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