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

时间:2017-03-02 23:34:37

标签: c++ file line-by-line

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!

1 个答案:

答案 0 :(得分:3)

您需要在输入语句中使用std:boolalpha,就像您对输出所做的那样:

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

否则,C ++在读取布尔变量时期望看到'0'或'1',而不是'false'或'true'。