C ifstream只读一个单词的数字

所以我想将.txt文件中的数字作为整数读取.

file.txt的:

hello 123-abc
world 456-def

当前代码:

int number;
ifstream file("file.txt");
while (!file.eof())
{
    file >> number; //123, 456
}

现在这显然不起作用,我一直试图解决这个“同时”,但我无法解决这个问题.

最佳答案 有很多方法可以做到这一点.您尝试过的方法不起作用,因为在流中的读取位置没有类似数字的东西.因此输入将失败,并且将设置流的失败位.你将永远循环,因为你只是在测试eof.
Read this获取更多信息.

一种简单的方法是一次读取一行,并通过利用std :: strtol的第二个参数来搜索第一个数字:

#include <iostream>
#include <string>
#include <experimental/optional>

std::experimental::optional<int> find_int_strtol( const std::string & s )
{
    for( const char *p = s.c_str(); *p != '\0'; p++ )
    {
        char *next;
        int value = std::strtol( p, &next, 10 );
        if( next != p ) {
            return value;
        }
    }
    return {};
}

int main()
{
    for( std::string line; std::getline( std::cin, line ); )
    {
        auto n = find_int_strtol( line );
        if( n )
        {
            std::cout << "Got " << n.value() << " in " << line << std::endl;
        }
    }
    return 0;
}

这有点笨拙,它也会检测到你可能不想要的负片.但这是一个简单的方法.如果提取了任何字符,则下一个指针将与p不同.否则该功能失败.然后将p递增1并再次搜索.它看起来像多项式搜索,但它是线性的.

我已经使用了C 17中的std :: optional,但我正在测试C 14编译器.这是为了方便.你可以在没有它的情况下编写函数.

实例is here.

解决这类问题的一种更灵活的方法是使用正则表达式.在这种情况下,您只需要一个简单的数字正则表达式搜索.以下只能找到正整数,但您也可以使用这种类型的模式来查找复杂数据.不要忘记包含标题< regex>:

std::experimental::optional<int> find_int_regex( const std::string & s )
{
    static const std::regex r( "(\\d+)" );
    std::smatch match;
    if( std::regex_search( s.begin(), s.end(), match, r ) )
    {
        return std::stoi( match[1] );
    }
    return {};
}

实例is here.

点赞