c++ - 用整数读取一行 C++

标签 c++ file input int

我正在做一个算法,我需要在 C++ 中读取一整行整数
我的输入文件是:
//////
5个
6 3 4 2 5
//////
我想读第二行,一个一个取整数
我不想将整数带入变量,因为我有内存限制(64 mb 的 ram)
我想直接从文件中获取整数
有没有什么办法可以用 c++(不是 c)

这个我试过了

fstream file;
file.open("file.txt");
int a;
file >> a;

但是有了这个我可以让它只读取“5”,如果我使用类似“getline();”的东西我无法得到我想要的每个整数
谢谢

最佳答案

不必将每个整数保存在其自己的变量中,只需重复使用同一个

fstream file("file.txt");
int a;
while (file >> a) {
   // Do your stuff with "a"
}

要跳过第一个数字(按照下面的问题),一个简单的方法是读取并丢弃整数一次:

fstream file("file.txt");
int a;
file >> a; // Do nothing with a → Discard the first value
while (file >> a) {
   // Do your stuff with "a"
}

关于c++ - 用整数读取一行 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27189220/

相关文章:

c++ - 输出 cout 是感叹号。 C++

java - 写入资源文件java?

java - 是什么让文件变成文件夹?

jquery - 如何使用jquery获取输入类型?

c++ - 垂直工具栏上的渲染子工具

c++ - 使用 pimpl-idiom 创建库

c++ - 用指定的字符结尾输入流,例如 '|'吗?

c++ - input_event 结构描述(来自 linux/input.h)

c++ - _declspec( novtable ) 什么时候不安全?

C: 扫描的双数组值为什么变化?