当我运行程序时,输出窗口会打印出“!Loading Data ...”行,但似乎它无休止地陷入了循环。据我所知,while循环设置正确,但是在拔掉插头后我很茫然。
ifstream myfile("Data.CS.txt");
if (!myfile) { //Always test the file open.
cout << "Error opening output file" << endl;
system("pause");
return -1;
}
cout << endl;
cout << "! Loading Data...";
while (getline(myfile, line)) {
string delimiter = "|";
string delimiter2 = "-=>";
size_t pos = 0;
string tempLine;
string tokenName;
string token;
string token2;
vector <string> storeTokenPairs;
tokenName = line.substr(0, pos);
tempLine = line.erase(0, pos + delimiter.length());
while ((pos = tempLine.find(delimiter2)) != string::npos) {
token = tempLine.substr(0, pos);
storeTokenPairs.push_back(token);
line.erase(0, pos + delimiter2.length());
}
for (int i=0; i<storeTokenPairs.size(); i++)
dictionary.emplace(tokenName, make_pair(storeTokenPairs[i], storeTokenPairs[i+1]));
}
答案 0 :(得分:2)
以下代码行是错误的:
while ((pos = tempLine.find(delimiter2)) != string::npos) {
token = tempLine.substr(0, pos);
storeTokenPairs.push_back(token);
line.erase(0, pos + delimiter2.length()); // <-- HERE
}
您永远不会修改tempLine
,因此,如果在delimiter2
中找到tempLine
,则循环将无限期地运行。
您需要将line
替换为tempLine
:
tempLine.erase(0, pos + delimiter2.length());
或者,实际上您根本不需要修改tempLine
,因为find()
将可选的起始索引作为输入:
size_t start = 0, pos;
while ((pos = tempLine.find(delimiter2, start)) != string::npos) {
token = tempLine.substr(start, pos-start);
storeTokenPairs.push_back(token);
start = pos + delimiter2.length();
}
if (start < tempLine.length()) {
token = tempLine.substr(start);
storeTokenPairs.push_back(token);
}