从文本文件C++跳过非整数
Skip non-integers from text file C++
>我有一个程序,可以从文本文件中读取整数并跳过非整数和奇怪的符号。然后文本文件如下所示:
# Matrix A // this line should be skipped because it contains # symbol
1 1 2
1 1$ 2.1 // this line should be skipped because it contains 2.1 and $
3 4 5
我必须打印出没有奇怪符号和非整数行的矩阵。即输出应该是:
1 1 2
3 4 5
我的代码
ifstream matrixAFile("a.txt", ios::in); // open file a.txt
if (!matrixAFile)
{
cerr << "Error: File could not be opened !!!" << endl;
exit(1);
}
int i, j, k;
while (matrixAFile >> i >> j >> k)
{
cout << i << ' ' << j << ' ' << k;
cout << endl;
}
但是当它获得第一个 # 符号时它会失败。请问有人帮忙吗?
你的问题出在这段代码上。
int i, j, k;
while (matrixAFile >> i >> j >> k)
作业是"找出行是否包含整数">
但是你的代码说"我已经知道该行包含整数">
如果您设置为每行三个整数,我建议使用此模式:
#include <fstream>
#include <sstream>
#include <string>
std::ifstream infile("matrix.txt");
for (std::string line; std::getline(infile, line); )
{
int a, b, c;
if (!(std::istringstream(line) >> a >> b >> c))
{
std::cerr << "Skipping unparsable line '" << line << "'n";
continue;
}
std::cout << a << ' ' << b << ' ' << c << std::endl;
}
如果每行的数字数是可变的,则可以使用如下跳过条件:
line.find_first_not_of(" 0123456789") != std::string::npos
当然
,这在#
字符处失败:#
不是整数,因此将其作为整数读取会失败。你可以做的是尝试读取三个整数。如果此操作失败并且您尚未达到 EOF(即matrixAFile.eof()
产生 false
,您可以clear()
错误标志,并将所有内容ignore()
到换行符。错误恢复将如下所示:
matrixAFile.clear();
matrixAFile.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
请注意,如果您失败了,您需要救助,因为eof()
true
。
由于这是一个作业,所以我没有给出完整的答案。
Read the data line by line to a string(call it str),
Split str into substrings,
In each substring, check if it's convertible to integer value.
另一个技巧是读取一行,然后检查每个字符是否在 0-9 之间。如果您不需要考虑负数,它就会起作用。
我想
我只是一次读一行作为字符串。我会将字符串复制到输出中,只要它只包含数字、空格和(可能(-
.
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址
- 是否基于数组B整数打印数组A中的整数
- 如何在C++中将整数转换为其数字数组