Search code examples
c++iofstream

Reading and storing integers in a file


I have a file.txt such as :

15 25 32 // exactly 3 integers in the first line. 
string1
string2
string3
*
*
*
*

What I want to do is, reading 15,25,32 and store them into lets say int a,b,c;

Is there anyone to help me ? Thanks in advance.


Solution

  • You can use a std::ifstream to read file content:

    #include <fstream>
    std::ifstream infile("filename.txt");
    

    Then you can read the line with the numbers using std::getline():

    #include <sstream>
    #include <string>
    std::string line;
    std::getline(infile, line);
    

    Then, you can use a std::istringstream to parse the integers stored in that line:

    std::istringstream iss(line);
    int a;
    int b;
    int c;
    
    iss >> a >> b >> c;