为什么这个for循环不执行?

Mau*_*rus 0 c++ for-loop getline

我正在为一个练习编写一个程序,该程序将从文件中读取数据并将其格式化为可读.到目前为止,我有一些代码可以将标题与其下的数据分开.这里是:

int main() {
    ifstream in("records.txt");
    ofstream out("formatted_records.txt");
    vector<string> temp;
    vector<string> headers;
    for (int i = 0; getline(in,temp[i]); ++i) {
        static int k = -1;
        if (str_isalpha(temp[i])) {
            headers[++k] = temp[i];
            temp.erase(temp.begin() + i);
        }
        else {
            temp[i] += "," + headers[k];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

(str_isalpha()只是一个适用isalpha()于字符串中每个字符的函数.)现在,此程序中的for循环不执行,我无法弄清楚原因.有人知道吗?

编辑:按照建议,我改为

string line;
for (int i = 0; getline(in,line); ++i) {
    temp.push_back(line);
Run Code Online (Sandbox Code Playgroud)

仍然完全跳过for循环.

Ale*_*lli 5

vector<string> temp;做一个空的向量.当您尝试阅读时temp[0],这是未定义的行为.你应该将getline第二个参数传递给一个单独的string变量,比如说string foo;在循环之前,然后temp.push_back(foo);作为循环体中的第一个指令.