当我运行程序时,输出窗口会打印出“!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]));
}

最佳答案

以下代码行是错误的:

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

关于c++ - 程序永远不会进入我可以输入信息的部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55151394/

10-10 23:00