【问题标题】:Reading from a file C++ (Line by line - mixed variables)从文件 C++ 中读取(逐行 - 混合变量)
【发布时间】:2017-07-22 22:06:48
【问题描述】:

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

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

  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() ,但没有任何组合奏效。

提前谢谢你!

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢。现在工作:)
    • 如果有效,您应该投票并接受答案。
    • 不确定如何接受 - 本网站的新手。编辑:找到它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 2014-06-21
    • 2012-06-13
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2010-12-24
    相关资源
    最近更新 更多