我正在编写一个代码来标记一个字符串 wrt 分隔符“,”。
void Tokenize(const string& str, vector<string>& tokens, const string& delimeters)
{
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
int main()
{
string str;
int test_case;
cin>>test_case;
while(test_case--)
{
vector<string> tokens;
getline(cin, str);
Tokenize(str, tokens, ",");
// Parsing the input string
cout<<tokens[0]<<endl;
}
return 0;
}
它在运行时给出段错误。当我调试它时,这条线
cout<<tokens[0]<<endl
是问题的原因。我不明白为什么,因为在 cplusplus.com它使用 [ ] 运算符来访问 vector 的值
最佳答案
cin>>test_case; // this leaves a newline in the input buffer
while(test_case--)
{
vector<string> tokens;
getline(cin, str); // already found newline
Tokenize(str, tokens, ","); // passing empty string
如果不查看您的 Tokenize 函数,我会猜测一个空字符串会导致一个空 vector ,这意味着当您打印 tokens[0]
时,该元素实际上并不存在。在调用 getline
之前,您需要确保输入缓冲区为空。例如,您可以在输入号码后立即调用 cin.ignore()
。
您也可以放弃 operator>>
,而只使用 getline。然后使用您喜欢的方法将字符串转换为数字。
关于c++ - Vectors 上的数组下标运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8773131/