如何在c++中读取格式化文件
how to read the formatted file in C++
我有以下格式。每行有两个整数,文件以"*"结尾。我如何从文件中读取这两个数字?谢谢。
4 5
7 8
78 89
* //end of file
编辑
我知道这两个数字,但不知道如何处理"*"。如果我将每个数字存储为整数类型并通过cin
读取它们。但是最后一行是字符串类型。所以问题是,我读它作为一个整数,但它是字符串,我不知道如何判断它是否是*或不是。
我的代码如下(这显然是错误的):
string strLine,strChar;
istringstream istr;
int a,b;
while(getline(fin,strChar))
{
istr.str(strLine);
istr>> ws;
istr>>strChar;
if (strChar=="*")
{
break;
}
istr>>a>>b;
}
您可以简单地从ifstream
对象中提取数字,直到它失败。
std::ifstream fin("file.txt");
int num1, num2;
while (fin >> num1 >> num2)
{
// do whatever with num1 and num2
}
我更喜欢使用老式的fscanf()方法,请参阅MSDN上一个简单而直接的示例。
- 作为第一步,将整行读入字符串缓冲区
- 检查是否等于"*"
- 如果不是,使用sscanf()解析两个整数
解决方法是使用std::istream
逐行读取文件。然后,处理每个输入行并将数字存储到一个列表中。
// open the file.
std::string path = "path/to/you/file";
std::ifstream file(path.c_str());
if (!file.is_open()) {
// somehow process error.
}
// read file line by line.
std::vector< std::pair<int,int> > numbers;
for (std::string line; std::getline(file,line);)
{
// prepare to parse line contents.
std::istringstream parser(line);
// stop parsing when first non-space character is '*'.
if ((parser >> std::ws) && (parser.peek() == '*')) {
break;
}
// store numbers in list of pairs.
int i = 0;
int j = 0;
if ((parser >> i) && (parser >> j)) {
numbers.push_back(std::make_pair(i, j));
}
}
相关文章:
- 将从格式化文本文件读取的文本数据存储到链表
- 从格式化输入操作中获取读取字符数
- 在Windows上读取/写入未格式化的SD卡
- 如何读取和处理格式化的日期,如 01/11/1998、星期日(10000 个输入)C++
- 用C++读取带多个分隔符的格式化数据
- 使用c++只读取已格式化和未格式化数据的文件中的已格式化数据
- 读取 *.mhd/*.raw 在 ITK 中格式化 3D 图像
- 如何读取时间输入并格式化输出
- 在 c++ 中读取格式化的文本文件
- C++从格式化的.txt文件中读取
- std::getline()从流中读取格式化的输入后读取错误的数据
- 使用cin读取格式化输入
- 如何为相邻列表读取格式化文件
- 使用C++读取格式化文件
- 扫描 读取格式化输入
- 在c++中读取格式化数据的最简单/最清晰的方法
- 如何在c++中读取格式化文件
- 使用 ifstream 提取运算符C++>>从文件中读取格式化数据
- 从大文件中读取格式化数据的最有效方法是什么
- 使用迭代器读取格式化流是件好事吗