Search code examples
c++istream

How to read integers from a line in C++?


I want to read integers in a line from a file.

For example the line is : 3/2+5-5

I think I need to use >>, but it stopped because of the characters;

I also try to use other functions, but they are all for characters.


Solution

  • As the @Fang already pointed out, there's no easy way to do it. You can read the whole line and tokenize it via the following code:

    std::ifstream f("file.txt");
    
    std::string line;
    std::getline(f, line);
    
    std::vector<std::string> integers;
    boost::split(integers, line, boost::algorithm::is_any_of("+-*/"), boost::token_compress_on);
    
    // Then convert strings from the integers container to ints