如何从文件中获取数字行并忽略第一个数字

How to get line of numbers from file and ignore first number?

本文关键字:数字 第一个 获取 文件      更新时间:2023-10-16

所以,可以说我们有一个带有这些数字的text.txt文件:

4 5 15 10 20 5 5 15 10 20 25

在上面的示例中,该行中的第一个数字描述了该行中有多少个数字。其余的数字是我感兴趣的数字(我将在代码的后期对它们进行排序,但这不是我的问题关注的地方)。

我的问题是,我如何最好地选择每行数字(忽略第一个数字),将它们放入数组中,然后移动到下一行并执行相同的事情(将它们放入数组中,稍后将分类)?

我所有的Google搜索点都可以通过getline使用字符串来完成此操作,而没有真正指出使用INT来处理它。希望这里有人可以帮助我指向正确的方向。

以下是我将用来打开文件的基本代码:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int a;
    ifstream inputfile;
    //declare an input file
    inputfile.open("text.txt");
    while(//not sure best way to do this part)
    {
            //guessing I can use a for loop and place numbers in array 
            //based on first number in the row of numbers
    }
    return 0;
}

最明显的方法可能是读取使用std::getline的行,然后将字符串放入stringstream中,然后从那里读取数字(显然忽略第一个)。

我建议采用以下方法:

std::string line;
// Keep reading lines of text from the file.
// Break out of the loop when there are no more lines in the file.
while (getline(inputfile, line)){
   // Construct a istingstream from the line of text. 
   std::istringstream ss(line);
   // Read the numbers from the istingstream.
   // Process the numbers as you please.
}