我正在做一个算法,我需要在 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/