如何从文件中获取数字行并忽略第一个数字
How to get line of numbers from file and ignore first number?
所以,可以说我们有一个带有这些数字的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.
}
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- OpenGL:第二个VBO破坏了第一个VBO
- 将一个数字拆分为多个数字,每个数字只有一个有效位
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 在我的第一个C++程序中需要一些帮助(简单)
- 为什么我的代码在第一个 if 语句处中断?
- 是否可以从另一个类对象调用一个类函数而不继承第一个类
- 在将字符串转换为整数后,是否有一种方法可以保持数字的第一个零