简体   繁体   中英

looping over numbers from a txt file using fstream

I'm a bit new to C++ so I'm trying to keep things simple.

I'm trying to apply a loop that simply prints out each number from a txt file. And there are A LOT of numbers.

I've been trying to do this with a for loop but with no success. 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. I just want to take every number from the txt file and print it to the user until every number is printed.

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. The code assumes int and that <algorithm> and <iterator> are included.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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