逐个整数文件读取
integer by integer file reading
我想读取文件,以便它应该逐个整数地读取。我已经一行一行地阅读了它,但我想逐个整数地阅读它。
这是我的代码:
void input_class::read_array()
{
infile.open ("time.txt");
while(!infile.eof()) // To get you all the lines.
{
string lineString;
getline(infile,lineString); // Saves the line in STRING
inputFile+=lineString;
}
cout<<inputFile<<endl<<endl<<endl;
cout<<inputFile[5];
infile.close();
}
你应该这样做:
#include <vector>
std::vector<int> ints;
int num;
infile.open ("time.txt");
while( infile >> num)
{
ints.push_back(num);
}
循环将在到达 EOF 时退出,或者尝试读取非整数。要详细了解循环的工作原理,请阅读我的答案 这里, 这里 和 这里.
另一种方法是:
#include <vector>
#include <iterator>
infile.open ("time.txt");
std::istream_iterator<int> begin(infile), end;
std::vector<int> ints(begin, end); //populate the vector with the input ints
您可以使用
operator>>
从 fstream 读取到 int
int n;
infile >> n;
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中