c++ - 在循环中使用getline,存储到数组

标签 c++

使用 getline 存储信息,我想要一个数组,它在文本文件中存储一整列,使用 '/' 作为分隔符,但是当创建一个循环时第一行并将其存储在 a[i] 等中,然后移至下一行。`

const int MAX = 20;
int main(){

    string menuname;
    string a[MAX];
    string d[MAX];
    string b[MAX];
    string c[MAX];
    string line;
    bool error = false;
    ifstream openFile;
    int counter = 0;

    do{
        cout  << "Please enter the name of the menu you would like to open: ";
        cin >> menuname;
        menuname +=  ".txt";
        openFile.open(menuname.c_str());
        if(openFile.fail()){
            cerr << "Unable to open file, please re-enter the name.\n";
            error = true;
        }
    //Determine how many lines long the text file is
        while(getline(openFile, line)){
            ++counter;
        }
       //Testing the counter
    cout << counter;
    }while(error == true);

    while(! openFile.eof()){
         for(int i = 0; i < counter; i++){
            getline( openFile, a[i], '/');
            getline( openFile, b[i], '/');
            getline( openFile, c[i], '/');
            getline( openFile, d[i]);
        }
    }
    for(int i = 0; i < counter; i++){
        cout << a[i] << b[i];
    }
}

当我运行程序时目前没有错误,我已经通过显示输出来测试计数器变量,它工作正常,但在程序的底部我创建了一个小测试,它应该打印一些 2我存储的数组,但它不打印任何内容,程序在显示计数器的值后结束。

最佳答案

问题是当你去实际存储数据时,你在文件的末尾。

while(getline(openFile, line)){
    ++counter;
}

从头到尾读取文件,然后在字符串上设置 EOF 标志。然后你就可以

while(! openFile.eof()){
     for(int i = 0; i < counter; i++){
        getline( openFile, a[i], '/');
        getline( openFile, b[i], '/');
        getline( openFile, c[i], '/');
        getline( openFile, d[i]);
    }
}

并且由于设置了 EOF 标志,因此永远不会执行 while 循环。由于您真正需要计数器的只是末尾的显示循环,我们可以将计数器循环和读取循环合并为一个循环,例如

while(getline( openFile, a[counter], '/') && getline( openFile, b[counter], '/') &&
      getline( openFile, c[counter], '/') && getline( openFile, d[counter])){
    counter++;
}

现在我们读取整个文件并计算读取的行数。

关于c++ - 在循环中使用getline,存储到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37034999/

相关文章:

c++:打印函数返回的字符串 vector

c++ - 针对具有 gtest 程序的以下情况进行设计

c++ - 错误 : no type named 'vector' in namespace 'std'

c++ - 解密未找到函数重载错误消息

c++ - 访问命名空间外的内部枚举值

c++ - Opengl减少制服的使用

c++ - 有没有办法为 cv QueryFrame 或 cv GrabFrame 设置起始帧?

c++ - 如何在不终止主应用程序的情况下卸载 ActiveX 的 ocx 以允许覆盖 ocx?

c++ - 访问说明符和性能

c++ - 相同的外部结构只有一个功能不同