如何在C ++中循环读取.txt文件中的字符串

时间:2018-07-04 11:56:28

标签: c++

我的代码:

#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string index[8];

int main() {
    int count = 0;
    ifstream input;
    //input.open("passData.txt");
    while (true) {
        input.open("passData.txt");
        if (!input) {
            cout << "ERROR" << endl;
            system("pause");
            exit(-1);
        }
        else {
            if (input.is_open()) {
                while (!input.eof()) {
                    input >> index[count];
                    count++;
                }
            }
            for (int i = 0; i < 8; i++) {
                cout << index[i] << endl;
            }
        }
        input.close();
    }
    return 0;
}

我的方法:从头开始打开文件,然后在读取行后立即将其关闭。另外,每一行都应该是数组中的单个条目。

但是,在迭代器中名为“ xutility”的文件中出现错误。 输出为“ passData.txt”文件,仅读取一次,然后显示错误。

所以,我的问题是:如何循环读取数组条目中文件的每一行?

谢谢!

3 个答案:

答案 0 :(得分:1)

我在这段代码中看到的问题是,您不会像以往一样打破无限循环。因此,您继续增加count,最终它超出了名为index的字符串数组的范围。

答案 1 :(得分:0)

看看下面的代码,我认为它可以完成您的任务,但是它更简单:

string strBuff[8];
int count = 0;
fstream f("c:\\file.txt", ios::in);
if (!f.is_open()) {
    cout << "The file cannot be read" << endl;
    exit(-1);
}
while (getline(f, strBuff[count])) {
    count++;
}

cout << strBuff[3] << endl;

答案 2 :(得分:0)

从流中提取时,应检查结果,而不是事先进行测试。

您不需要调用open,接受字符串的构造函数将执行此操作。您不需要调用close,析构函数会这样做。

您应该只输出已阅读的行。

请注意,如果文件用完了或者读取了8行,则应同时停止

您可以舍弃大部分已写的内容。

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    string index[8];
    std::size_t count = 0;   
    for(std::ifstream input("passData.txt"); (count < 8) && std::getline(input, index[count]); ++count)
    { 
        // this space intentionally blank
    }
    for(std::size_t i = 0; i < count; ++i)
    {
        std::cout << index[i] << std::endl;
    }
}