C++ "string subscript out of range" 问题

C++ "string subscript out of range" problem

请帮忙调试。编译器给我一个错误 'string subscript out of range error'.

这部分程序的想法是从一个文本文件中读入多行并将它们组合成一个字符串。最后一行有一个分号';'最后。

例如:

"猫

坐在垫子上

自己";

最后的字符串是:“猫自己坐在垫子上”;

有我的代码:

int main()
{
    string temp;
    char temps[1000];
    while (true) {
        cout << "Please input file name: ";// user input file name
        getline(cin, fileName);
        ifstream inFile(fileName);
        if (!inFile.is_open())// error
        {
            cout << "File cannot be opened" << endl;
            exit(1);
        }
        
        while (true) {
            inFile.getline(temps, 500);//read line from file
            temp = temps;

            while (temp[temp.length()-1] != ';') {// This while loop should combine each line which has no ';' at the end. However, when I load the example4.txt
                inFile.getline(temps, 500);      // the system will warn that "string subscript out of range". I do not know how to fix.
                temp = temp.append(temps);
            }
        }
   }
}

这里是错误发生的地方:

while (temp[temp.length()-1] != ';') {// This while loop should combine each line which has no ';' at the end. However, when I load the example4.txt
                inFile.getline(temps, 500);      // the system will warn that "string subscript out of range". I do not know how to fix.
                temp = temp.append(temps);
            }

感谢您的帮助!

temp.length() 将为空行变为零,然后 temp[temp.length()-1] 将超出范围。你应该检查一下。

//     add this condition
//     |
//     v
while (temp.length() == 0 || temp[temp.length()-1] != ';') {
    inFile.getline(temps, 500);
    temp = temp.append(temps);
}