c++fileline-by-line

Reading from a file C++ (Line by line - mixed variables)


Coding newbie here. C++ is my first language. Please include some explanation if possible.

I have to read lines from a file containing mixed variables. I am currently facing 2 issues:

  1. Looping the input statements so that I can read all lines. I am restricted to using the following code to do the loop:

    while(inputFile.peek() != EOF)

I do understand that this should check next char and if its EndOfFile it will break the loop but I can't get it to work.

  1. Reading a string preceded by a bool (skipping the whitespace). To skip the whitespace, I am supposed to use:

    while(inputFile.peek() == ' ') inputFile.get();

The File contents are as follows:

Car    CN    819481   maintenance   false    NONE
Car    SLSF   46871   business      true     Memphis
Car    AOK      156   tender        true     McAlester

My code is below. I've omitted the main() function as the only thing it does is call input().

#include <iostream> //used in main()
#include <iomanip>
#include <string>
#include <fstream>  //to work with file
#include <cstdlib> //for exit() function
using namespace std;

void input(){
    ifstream inputFile;
    string type, rMark, kind, destination;
    int cNumber;
    bool loaded;

    inputFile.open("C:\\My Folder\\myFile.txt"); //open file

    if (!inputFile){
        cerr << "File failed to open.\n";
        exit(1);
    }

    //read file contents
    while(inputFile.peek() != EOF){
    //initially I had >>destination in the statement below as well 
    //but that gave me the same results.
        inputFile >> type >> rMark >> cNumber >> kind >> loaded; 

    //skip whitespace  
        while(inputFile.peek() == ' '){
            inputFile.get();
            }
    //get final string
        getline(inputFile, destination);
        cout << type << " " << rMark << " " << cNumber << " " << kind << " ";
        cout << boolalpha << loaded << " " << destination << endl;
    }

    inputFile.close();  //close file
} //end input()

After running the program I get:

Car CN 819481 maintenance false

So the first line gets read up until the bool value (and the last string gets omitted), and the loop is not working (or it is but it's reading something it shouldn't?). I've tried moving the .peek() and .gets() around but no combination has worked.

Thank you in advance!


Solution

  • You need to use std:boolalpha in your input statement, just as you did for the output:

    inputFile >> type >> rMark >> cNumber >> kind >> boolalpha >> loaded; 
    

    Otherwise, C++ expects to see '0' or '1' when reading boolean variables, rather than 'false' or 'true'.