Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have some trouble with reading of a file in C++. I am able to read only integers or only alphabets. But I am not able to 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 am trying to do is, I am allowing the user to specify the input file he wants to read, and I am using getline to obtain each line. I can use the method of tokens to read only integers or only alphabets. But I am not able to read a mix of both. If my input file is

2 1 89ab

8 2 16ff

What is the best way to read this file?

Thanks a lot in advance for your help!

like image 538
Sista Avatar asked Nov 04 '22 23:11

Sista


1 Answers

I'd use a std::stringstream, and use std::hex since 89ab and 16ff look like hex numbers.

Should look like this:

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

You will need to #include <sstream>

like image 151
Marlon Avatar answered Nov 09 '22 14:11

Marlon