【问题标题】:looping over numbers from a txt file using fstream使用 fstream 从 txt 文件中循环数字
【发布时间】:2018-10-27 23:48:58
【问题描述】:

我对 C++ 有点陌生,所以我尽量保持简单。

我正在尝试应用一个简单地从 txt 文件中打印出每个数字的循环。还有很多数字。

我一直在尝试使用 for 循环来执行此操作,但没有成功。这只是我的尝试之一:

int main() {
    fstream myFile;
    myFile.open("resources/numbers.txt");

    if (myFile) {
        cout << "This file is opened\n";
    }
    else
        return EXIT_FAILURE;

    for (i = 1; i<n; i++){
        myFile >> n;
        cout << n;
    }

    return 0;
}

我不想使用数组或 getLine。我只想从 txt 文件中取出每个数字并将其打印给用户,直到每个数字都被打印出来。

有没有简单的方法可以做到这一点?

谢谢一百万!

【问题讨论】:

  • 您应该始终检查您是否在尝试读取if (myFile &gt;&gt; n)之后成功地读取了文件。 yiu 真的想将in 比较吗?你可能宁愿利用阅读的成功。

标签: c++ loops fstream


【解决方案1】:

这是我在文件中打印数字的方式:

std::copy(std::istream_iterator<int>(myFile),
          std::istream_iterator<int>(),
          std::ostream_iterator<int>(std::cout, “\n”));

在您的示例中,您没有声明 n,因此不清楚正确的类型是什么。代码假定int 并且包含&lt;algorithm&gt;&lt;iterator&gt;

【讨论】:

    【解决方案2】:
    #include <cstdlib>  // EXIT_FAILURE
    #include <iostream>
    #include <fstream>
    
    int main()
    {
        std::ifstream myFile{ "resources/numbers.txt" };  // use c-tor to open
        //   ^ ifstream ... we only want to read
    
        if (!myFile.is_open()) {
            std::cerr << "File couldn't be opened for reading :(\n\n";
            return EXIT_FAILURE;
        }
    
        std::cout << "File is open for reading.\n\n";
    
        int number;
        while(myFile >> number) // as long as integers can be extracted from the stream,
            std::cout << number << '\n';  // print them.
    } // no need to return anything as main() returns 0 when not return statement
      // is present.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多