从文件中读取C++代码(逐行 - 混合变量)

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()函数,因为它唯一的作用就是调用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(),但没有任何组合可行。
提前感谢!
1个回答

3
您需要在输入语句中使用std:boolalpha,就像输出语句中一样:
inputFile >> type >> rMark >> cNumber >> kind >> boolalpha >> loaded; 

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

谢谢。现在可以工作了 :) - gboyn
如果它能够正常工作,您应该点赞并接受这个答案。 - user31264
不确定如何接受 - 对这个网站还不熟悉。 编辑:找到了。 - gboyn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接