简体   繁体   English

使用fstream循环遍历txt文件中的数字

[英]looping over numbers from a txt file using fstream

I'm a bit new to C++ so I'm trying to keep things simple. 我对C ++有点陌生,所以我试图使事情保持简单。

I'm trying to apply a loop that simply prints out each number from a txt file. 我正在尝试应用一个循环,该循环只是从txt文件中打印出每个数字。 And there are A LOT of numbers. 并且有很多数字。

I've been trying to do this with a for loop but with no success. 我一直在尝试使用for循环来执行此操作,但没有成功。 Here's just one of my attempts: 这只是我的尝试之一:

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;
}

I'd prefer not to use arrays or getLine. 我不想使用数组或getLine。 I just want to take every number from the txt file and print it to the user until every number is printed. 我只想从txt文件中提取每个数字,然后将其打印给用户,直到打印每个数字为止。

Is there an easy way to do this? 是否有捷径可寻?

Thanks a million! 太感谢了!

#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.

Here is how I'd print the number in the file: 这是我在文件中打印数字的方式:

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

In you example you didn't declare n so it isn't clear what the proper type is. 在您的示例中,您没有声明n因此尚不清楚正确的类型是什么。 The code assumes int and that <algorithm> and <iterator> are included. 该代码假定为int并且包含<algorithm><iterator>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM