C++ 中有没有一种方法可以检查打开的 fstream 文件的一行是否包含多个整数?

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

我已经 myfile.in 打开了以下文本:

1
4 5
3

对每个数字 while (myfile >> var) cout << var << endl; 将一一输出每个整数:

1
4
5
3

有什么方法可以检查 myfile.in 的所有行并输出超过 1 个整数的行?对于上面的例子:

4 5

4
5

您可以使用 std::getlinestd::istringstream 的组合,如下所示。解释在评论里。

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