简体   繁体   中英

Reading Numbers from a File

I have a file with many numbers. The file looks like "192 158 100 0 20 200" basically like that. How can I load the files number values 1 at a time and display them on the screen in C++?

try something like this:

int val;
std::ifstream file("file");
while (file >> val)        
    std::cout << val;

The following program should print each number, one per line:

#include <iostream>
#include <fstream>

int main (int argc, char *argv[]) {
    std::ifstream ifs(argv[1]);
    int number;

    while (ifs >> number) {
       std::cout << number << std::endl;
    }
}

Please consider the following code:

    ifstream myReadFile;
    myReadFile.open("text.txt");
    int output;
    if (myReadFile.is_open())
    {
        while (fs >> output) {   
            cout<<output;
        }
    }

//Of course closing the file at the end.
myReadFile.close();

As well, please include the iostream and fstream inside your code when using the example above.

Note that you need to start open a filestream to read and you can try to read it char by char and detect is there any white space in between it.

Good luck.

#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>

int main() {
    std::ifstream fs("yourfile.txt");
    if (!fs.is_open()) {
        return -1;
    }

    // collect values
    // std::vector<int> values;
    // while (!fs.eof()) {
    //    int v;
    //    fs >> v;
    //    values.push_back(v);
    // }
    int v;
    std::vector<int> values;
    while (fs >> v) {
        values.push_back(v);
    }
    fs.close();    

    // print it
    std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, " "));

    return 0;
}

Another way of doing it:

std::string filename = "yourfilename";

//If I remember well, in C++11 you don't need the
//conversion to C-style (char[]) string.
std::ifstream ifs( filename.c_str() );


//Can be replaced by ifs.good(). See below.
if( ifs ) {
    int value;

    //Read first before the loop so the value isn't processed
    //without being initialized if the file is empty.
    ifs >> value;

    //Can be replaced by while( ifs) but it's not obvious to everyone
    //that an std::istream is implicitly cast to a boolean.
    while( ifs.good() ) { 
        std::cout << value << std::endl;
        ifs >> value;       
    }
    ifs.close();
} else {
    //The file couldn't be opened.
}

The error-handling can be done in many ways through.

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