程序永远不会到达我可以输入信息的部分

Program never gets to the part where I can input information

当我 运行 程序时,输出 window 打印出“!正在加载数据...”这一行,但它似乎陷入了无限循环。据我所知,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,因此如果在 tempLine 中找到 delimiter2,则循环将无限运行。

您需要将 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);
}