Search code examples
c++iostreamifstream

Reading from file inserting values into ints and chars C++


I wanted to read the short binaries from an external file with the key.

3 A 0100 3 E 0101 3 G 0110 3 M 0111 3 N 1010 3 H 1011 2 S 100 1 T 00 2 10 2 I 111

3 is in an int called pos

A is in a char called al

0100 is in an array called bin etc...


Solution

  • Open your file, read the file data line by line and extract what you need from the line.

      std::string line;
      ifstream read;
      //open data files     
      read.open(file_name);
      if(read.is_open())
        cout << "File ./" << file_name << " is open.\n";
      else {
        cout << "Error opening " << file_name << ".\n";
        exit(0);
        }
    
        while (std::getline(read, line))
        {
        // line =3 A 0100 3 E 0101 3 G 0110 3 ...     
         std::istringstream iss (std::move(line));
         std::string val_str, al, bin; 
            while(! iss.str().empty())
            {
                try{
                    iss>>val_str;               
                    int val= std::stoi(val_str);     //val = 3 in the first run of the while loop
                    iss >> al;               //al = A  in the first run of the while loop
                    iss >> bin
                    // you can use val, al ,bin
                }catch(..){
                    break;
                }
            }
        }