[英]Array subscript operator on Vectors
I was writing a code to tokenize a string wrt delimeters ",". 我正在编写一个代码来标记字符串wrt deimeters“,”。
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;
}
It gives segmentation fault on running. 它给出了运行时的分段错误。 When I debugged it the line
当我调试它的线
cout<<tokens[0]<<endl
was the cause of problem.I can't understand why because at cplusplus.com it uses the [ ] operartors for accesing the values of vectors 是问题的原因。我无法理解为什么因为在cplusplus.com它使用[]操作符来访问向量的值
Is it possible that the read using std::getline()
wasn't successful? 使用
std::getline()
的读取是否可能不成功? In this case the string would be empty and using the subscript operator would crash. 在这种情况下,字符串将为空,使用下标运算符将崩溃。 You should always test whether reading was successful after trying to read, eg:
在尝试阅读后,您应该始终测试阅读是否成功,例如:
if (std::getline(std::cin, str)) {
// process the read string
}
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
Without looking at your Tokenize function, I would guess that an empty string results in an empty vector, which means when you print tokens[0]
, that element does not actually exist. 在不查看Tokenize函数的情况下,我猜测空字符串会导致空向量,这意味着当您打印
tokens[0]
,该元素实际上不存在。 You need to make sure your input buffer is empty before you call getline
. 在调用
getline
之前,您需要确保输入缓冲区为空。 You could put a call to cin.ignore()
right after your number input, for example. 例如,您可以在输入数字后
cin.ignore()
拨打cin.ignore()
。
You could also forgo operator>>
, and only use getline. 你也可以放弃
operator>>
,只使用getline。 Then do string to number conversions with your favorite method. 然后使用您喜欢的方法对字符串进行数字转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.