从文件,特定行中仅读取数字

Reading only numbers from a file, from a specific line

本文关键字:读取 数字 文件      更新时间:2023-10-16

我正在尝试从包含4行的标头的数据文件中读取,并且还有一个我将存储在2D int array

的数字列表

例如

标题

标题

标题

标题

int

int

int

int

......

我需要以某种方式跳过包含文本的标头线,仅使用int行并将其存储到上述2D数组中。当我打开文件并通过它搜索时,它根本不存储任何值,因为一开始就使用了文本。我已经尝试了多个if语句和其他事情来解决这个问题,但是已经工作了。

int main()
{
    ifstream imageFile;
    imageFile.open("myfile");
    if (!imageFile.is_open())
    {
        exit (EXIT_FAILURE);
    }
    int test2[16][16];
    int word;
    imageFile >> word;
    while (imageFile.good())
        for (int i = 0; i < 16; i++)
        {
            for (int j = 0; j < 16; j++)
            {
                test2[i][j] = word;
                imageFile >> word;
            }
        }
}

如评论中所述,您需要先阅读标题 - 在这里,我只是将标题存储在trash变量中,该字符串是每次存储新标头时都会被覆盖的字符串:

std::string trash;
for (int i =0; i < 4; i++)
    std::getline(imageFile, trash);

该部分在您检查文件是否正确打开后进行,并将直接遵循您的原始代码,在该代码中您声明2D数组并读取整数。

在评论中也说过,您需要std::getline,它读取整个标题线,而不是一个单词,这是我答案的第一个版本(imageFile >> trash;)。

您可以通过REGEX和模式(修改2D数组的代码这只是可以从文件或字符串提取数字)的示例:

std::string ss;
ifstream myReadFile;
myReadFile.open("foo.txt");
char output[100];
if (myReadFile.is_open()) {
    while (!myReadFile.eof()) {
        myReadFile >> output;
        ss.append(output);
        ss.append("n");
    }
}
myReadFile.close();
std::regex rx(R"((?:^|s)([+-]?[[:digit:]]+(?:.[[:digit:]]+)?)(?=$|s))"); // Declare the regex with a raw string literal
std::smatch m;
std::string str = ss;
while (regex_search(str, m, rx)) {
    std::cout << "Number found: " << m[1] << std::endl; // Get Captured Group 1 text
    str = m.suffix().str(); // Proceed to the next match
}

输出:

Number found: 612
Number found: 551
Number found: 14124