Reading a combination of integers and characters from a file in C ++

I have some problems reading a file in C ++. I can only read integers or only alphabets. But I can not read both, for example, 10af, ff5a. My procedure is as follows:

int main(int argc, char *argv[]) {

if (argc < 2) {
    std::cerr << "You should provide a file name." << std::endl;
    return -1;
}

std::ifstream input_file(argv[1]);
if (!input_file) {
    std::cerr << "I can't read " << argv[1] << "." << std::endl;
    return -1;
}

std::string line;
for (int line_no = 1; std::getline(input_file, line); ++line_no) {
    //std::cout << line << std::endl;

         -----------
    }
       return 0;
 }

So what I'm trying to do, I allow the user to specify the input file that he wants to read, and I use getline to get each line. I can use the token method to read only integers or only alphabets. But I do not know how to read a mixture of both. If my input file

2 1 89ab

8 2 16ff

What is the best way to read this file?

Thank you for your help!

+5
source share
2 answers

std::stringstream std::hex, 89ab 16ff .

:

std::string line;
for (int line_no = 1; std::getline(input_file, line); ++line_no)
{
    std::stringstream ss(line);
    int a, b, c;

    ss >> a;
    ss >> b;
    ss >> std::hex >> c;
 }

#include <sstream>

+2

std::string s;
while (input_file >> s) {
  //add s to an array or process s
  ...
}

std::string, . , . >> , .

0

All Articles