Search code examples
c++fstreamifstream

Is there a way in C++ to check if a line of an opened fstream file contains multiple integers?


I have myfile.in opened with the following text:

1
4 5
3

Going for every number while (myfile >> var) cout << var << endl; will output each integer one by one:

1
4
5
3

Is there any way I can check all the lines of myfile.in and output the lines with more than 1 integer? For the example above:

4 5

or

4
5

Solution

  • You can use a combination of std::getline and std::istringstream as shown below. The explanation is given in the comments.

    #include <iostream>
    #include<fstream>
    #include<string>
    #include <sstream>
    
    int main()
    {
        std::ifstream inputFile("input.txt");
        std::string line; 
        int num = 0; //for storing the current number
        int count = 0;//for checking if the current line contains more than 1 integer
        if(inputFile)
        {
            //go line by line 
            while(std::getline(inputFile, line))
            {
                std::istringstream ss(line);
                //go int by int 
                while(ss >> num)
                {
                    ++count;
                    //check if count is greater than 1 meaning we are checking if line contains more than 1 integers and if yes then print out the line and break
                    if (count > 1)
                    {
                        std::cout<<line <<std::endl;
                        break;
                    }
                    
                }
                //reset count and num for next line 
                count = 0;
                num = 0;
                
            }
            
        }
        else 
        {
            std::cout<<"input file cannot be opened"<<std::endl;
        }
        return 0;
    }
    

    Demo.