代码之家  ›  专栏  ›  技术社区  ›  Oliver Tworkowski

如何从C++中的.txt文件中读取字符串

c++
  •  0
  • Oliver Tworkowski  · 技术社区  · 7 年前

    我的代码:

    #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 回复  |  直到 7 年前
        1
  •  1
  •   pbn    7 年前

    我看到这段代码的问题是,你没有像以往一样打破无止境的循环。正因为如此,你不断地增加 count 它最终超出了字符串数组的范围 index .

        2
  •  0
  •   Caleth    7 年前

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

    你不需要打电话 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;
        }
    }
    
        3
  •  0
  •   Lion King    7 年前

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

    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;