从文本文件C++跳过非整数

Skip non-integers from text file C++

本文关键字:整数 C++ 文本 文件      更新时间:2023-10-16

>我有一个程序,可以从文本文件中读取整数并跳过非整数和奇怪的符号。然后文本文件如下所示:

# 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 之间。如果您不需要考虑负数,它就会起作用。

我想

我只是一次读一行作为字符串。我会将字符串复制到输出中,只要它只包含数字、空格和(可能(-.