[英]Array subscript operator on Vectors
我正在編寫一個代碼來標記字符串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;
}
它給出了運行時的分段錯誤。 當我調試它的線
cout<<tokens[0]<<endl
是問題的原因。我無法理解為什么因為在cplusplus.com它使用[]操作符來訪問向量的值
使用std::getline()
的讀取是否可能不成功? 在這種情況下,字符串將為空,使用下標運算符將崩潰。 在嘗試閱讀后,您應該始終測試閱讀是否成功,例如:
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
在不查看Tokenize函數的情況下,我猜測空字符串會導致空向量,這意味着當您打印tokens[0]
,該元素實際上不存在。 在調用getline
之前,您需要確保輸入緩沖區為空。 例如,您可以在輸入數字后cin.ignore()
撥打cin.ignore()
。
你也可以放棄operator>>
,只使用getline。 然后使用您喜歡的方法對字符串進行數字轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.