使用C++读取格式化文件
Formatted file reading with C++
我正在尝试从文件中读取所有整数并将它们放入数组中。我有一个包含以下格式的整数的输入文件:
3 74
74 1
1 74
8 76
基本上,每行包含一个数字,一个空格,然后是另一个数字。我知道在 Java 中我可以使用 Scanner 方法 nextInt(( 来忽略间距,但我在C++中没有找到这样的函数。
#include <fstream>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> arr;
std::ifstream f("file.txt");
int i;
while (f >> i)
arr.push_back(i);
}
或者,使用标准算法:
#include <algorithm>
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> arr;
std::ifstream f("file.txt");
std::copy(
std::istream_iterator<int>(f)
, std::istream_iterator<int>()
, std::back_inserter(arr)
);
}
int value;
while (std::cin >> value)
std::cout << value << 'n';
通常,流提取程序会跳过空格,然后翻译后面的文本。
// reading a text file the most simple and straight forward way
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
using namespace std;
int main () {
int a[100],i=0,x;
ifstream myfile ("example.txt");
if (myfile.is_open()) // if the file is found and can be opened
{
while ( !myfile.eof() ) //read if it is NOT the end of the file
{
myfile>>a[i++];// read the numbers from the text file...... it will automatically take care of the spaces :-)
}
myfile.close(); // close the stream
}
else cout << "Unable to open file"; // if the file can't be opened
// display the contents
int j=0;
for(j=0;j<i;j++)
{//enter code here
cout<<a[j]<<" ";
}
//getch();
return 0;
}
相关文章:
- 将从格式化文本文件读取的文本数据存储到链表
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 如何正确格式化csv文件?
- 简单的文本文件格式化在linux下崩溃,但在Windows中很好
- 在 Visual Studio 中格式化C++头文件
- 使用c++只读取已格式化和未格式化数据的文件中的已格式化数据
- 在C 或QT中格式化XML文件
- 加载格式化的二进制文件并将信息分配给结构 c++
- 在 c++ 中读取格式化的文本文件
- 格式化文件异常被 try catch 块忽略
- 以C++格式格式化 CSV 文件
- 我需要一些帮助以有组织的方式格式化文件
- 已知格式化文件中的数据排列
- 使用格式化结果解析搜索/替换头文件
- 在 cpp 文件中格式化 printf 语句
- 在未格式化的文本文件中插入回车
- C++从格式化的.txt文件中读取
- 高效地将格式化后的内容写入文件
- 使用 sscanf 、选项卡格式化日志文件
- 我可以列出将使用 astyle 格式化的文件吗?