3

编码新手在这里。C++ 是我的第一语言。如果可能,请提供一些解释。

我必须从包含混合变量的文件中读取行。我目前面临2个问题:

  1. 循环输入语句,以便我可以读取所有行。我仅限于使用以下代码来执行循环:

    while(inputFile.peek() != EOF)

我明白这应该检查下一个字符,如果它的 EndOfFile 它将打破循环,但我无法让它工作。

  1. 读取前面带有布尔值的字符串(跳过空格)。要跳过空格,我应该使用:

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

文件内容如下:

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

我的代码如下。我省略了这个main()函数,因为它唯一做的就是 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()

运行程序后,我得到:

Car CN 819481 maintenance false

所以第一行被读取直到布尔值(并且最后一个字符串被省略),并且循环不起作用(或者它正在读取它不应该读取的东西?)。我试过移动 .peek() 和 .gets() ,但没有任何组合奏效。

先感谢您!

4

1 回答 1

3

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

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

否则,C++ 期望在读取布尔变量时看到“0”或“1”,而不是“假”或“真”。

于 2017-03-02T23:56:45.490 回答