C ++ ifstream read only words

So, I would like to read the numbers from the .txt file as integers.

file.txt:

hello 123-abc
world 456-def

current code:

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

Now this clearly doesn't work, and I'm trying to solve it for "while", but I just can't get around this.

+4
source share
3 answers

There are several ways to do this. The method you tried does not work because there is no zero digit sitting at the read position in the stream. Thus, the input will fail, and the stream reset bit will be set. You loop forever, because you only check on eof. Read this for more information.

, 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;
}

, , , , . . next p, - . . p 1 . , .

std::optional ++ 17, ++ 14. . .

.

- . . , . <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 {};
}

.

+1

, , , , :

std::string currentLine = "";
std::string numbers = "";
ifstream file("file.txt");
if(file.is_open())
{
    while(std::getline(file, currentLine))
    {
        int index = currentLine.find_first_of(' '); // look for the first space
        numbers = currentLine.substr(index + 1, xyz);
    }
} 

xyz - (3 , ), , (index, currentLine.back() - index);

, , .

0

, . std::stoi std::vector.

std::ifstream file{"file.txt"};
std::vector<int> numbers;

for (std::string s; std::getline(file, s);) {
    s.erase(std::remove_if(std::begin(s), std::end(s),
        [] (char c) { return !::isdigit(c); }), std::end(s));
    numbers.push_back(std::stoi(s));
}

Alternatively, use std::regex_replaceto remove characters without numbers:

auto tmp = std::regex_replace(s, std::regex{R"raw([^\d]+(\d+).+)raw"}, "$1");
numbers.push_back(std::stoi(tmp));

Live example

0
source

Source: https://habr.com/ru/post/1676876/


All Articles