繁体   English   中英

从具有混合整数,字母和空格的文件中读取整数C ++

[英]Reading integers from a file with mixed integers, letters, and spaces C++

这是我在一周前完成的当前编程作业中添加的一种自我强加的额外信用问题。 分配涉及从文件中读取整数,每行有多个整数,每个整数之间用空格分隔。 使用while(inFile >> val)可以轻松实现这一点。

我面临的挑战是尝试从包含数字和字母的混合文件中读取整数,将所有连续的数字提取为由这些数字组成的单独整数。 例如,如果我正在从文本文件中读取以下行:

12f 356 48 r56 fs6879 57g 132e efw ddf312 323f

将要读取(和存储)的值是

12 f 356 48 r 56 fs 6879 57 g 132 e efw ddf 312 323 f

要么

12、356、48、56、6879、57、132、312和323

我花了整个下午的时间浏览cplusplus.com并阅读封面,以了解get,getline,cin等的详细信息,但我无法为此找到理想的解决方案。 我可以推断出的每种方法都涉及从整个文件中详尽地读取每个字符并将其存储到某种容器中,然后一次遍历一个元素并取出每个数字。

我的问题是从文件读取它们的过程中是否有办法做到这一点? 即get,getline,cin和company的功能是否支持这种复杂的操作?

一次读取一个字符并进行检查。 有一个变量,用于维护当前正在读取的数字,以及一个标志,告诉您是否正在处理数字。

如果当前字符是数字,则将当前数字乘以10,然后将数字添加到数字中(并设置“处理数字”标志)。

如果当前字符不是数字,并且您正在处理数字,则您已到达数字的末尾,应将其添加到输出中。

这是一个简单的这样的实现:

std::vector<int> read_integers(std::istream & input)
{
    std::vector<int> numbers;

    int number = 0;
    bool have_number = false;

    char c;

    // Loop until reading fails.
    while (input.get(c)) {
        if (c >= '0' && c <= '9') {
            // We have a digit.
            have_number = true;

            // Add the digit to the right of our number.  (No overflow check here!)
            number = number * 10 + (c - '0');
        } else if (have_number) {
            // It wasn't a digit and we started on a number, so we hit the end of it.
            numbers.push_back(number);
            have_number = false;
            number = 0;
        }
    }

    // Make sure if we ended with a number that we return it, too.
    if (have_number) { numbers.push_back(number); }

    return numbers;
}

请观看现场演示 。)

现在,您可以执行以下操作以从标准输入中读取所有整数:

std::vector<int> numbers = read_integers(std::cin);

这将与std::ifstream同样有效。

您可能会考虑将函数作为模板,其中参数指定要使用的数字类型-这将使您(例如)切换到long long int而不更改函数,如果您知道文件将包含大量数字,不适合int内部。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM