【问题标题】:unexpected getline behavior意外的 getline 行为
【发布时间】:2020-07-23 15:15:36
【问题描述】:

最初尝试使用 char* 读取数据,但切换到字符串导致出现的行为就像缺少空终止符一样。使问题最小化,但仍然得到非常奇怪的输出

int main(int argc, char * argv[]){


    // file one:  flightData
    std::ifstream inFile1(argv[1]);
    if (!inFile1.is_open())
    {
        std::cout << "Could not open the file 1." << std::endl;
        return -1;
    }
    // file two: flightPlans
    std::ifstream inFile2(argv[2]);
    if (!inFile2.is_open())
    {
        std::cout << "Could not open the file 2." << std::endl;
        return -1;
    }
    //File three: output
    std::ofstream outputfile(argv[3]);
    if (!outputfile.is_open())
    {
        std::cout << "Could not open the output file" << std::endl;
        return -1;
    }
    std::string buffer;


    getline(inFile1, buffer);
    std::cout<<buffer<<std::endl;
    while (getline(inFile1, buffer)) {
        std::cout<<buffer;
        std::cout<<"help";
    }

   // flightPlanner system(inFile1);
  //  system.printF();
//    system.planFlights(inFile2,outputfile);

    return 0;
}

输出是

4
helpDallas|Austin|50|50help

我很确定这是不正确的,有趣的是,当我将 endl 添加到 cout 缓冲区时,它给了我输出,我希望不太确定发生了什么

inFile1

4
Dallas|Austin|50|50
Dallas|Austin|50|50
Dallas|Austin|50|50
Dallas|Austin|50|50

当我在调试器中运行时,我得到了我期望的输出:

4

Dallas|Houston|50|50
helpDallas|Houston|50|50
helpDallas|Houston|50|50
helpDallas|Houston|50|50help

知道会发生什么吗?

【问题讨论】:

    标签: c++ string file io getline


    【解决方案1】:

    您需要刷新标准输出吗?

    std::cout << std::flush;
    

    你的 shell 有没有可能吃掉你的输出? 尝试将输出添加到“cat -A”:

    ./a.out | cat -A
    

    (由评论驱动 - 我可能不知道我在说什么^_^)

    【讨论】:

      猜你喜欢
      • 2011-03-31
      • 2014-03-20
      • 2017-04-05
      • 1970-01-01
      • 2016-09-13
      • 2020-10-04
      • 2016-07-16
      • 2016-05-10
      • 2021-08-23
      相关资源
      最近更新 更多