无法使用 std::getline() 与 ifstream 和 ofstream 一起工作

unable to use std::getline() to work alongside ifstream and ofstream

如果我将代码分成两个单独的程序,它会像我想要的那样工作(将我创建文件的第 3 部分和我尝试以用户身份访问文件的第 2 部分分开);但是一旦我将代码放入单个程序中(见下文),我就无法使用 getline() 方法从标准输入中收集输入;程序一直执行到最后,没有在源代码中的 getline 方法处停止收集用户输入。

我阅读了一堆已回答的问题并尝试以下无济于事:

  1. 键入 #include <string>
  2. 键入 outFile.clear();
  3. 键入 inFile.clear();
  4. 我在过去 3 小时内尝试了其他方法,例如注释掉部分代码以查看是否可以查明问题所在。

该程序的目的是创建一个文本文件,然后从 'teacher' 中获取 2 个成绩并将它们放入文本文件中。第二部分要求用户输入文件路径;然后代码提供文件中的平均成绩。问题是下面的代码永远不会停止以允许用户输入文件的路径。

#include <iostream>
#include <fstream> //file steam for access to objects that work with files
#include <cstdlib>

//using namespace std;

int main()
{
//****************PART #1 - CREATE A FILE & ADD DATA *************************************************
std::cout << "Part #1 - create file & put data into it.\n" << std::endl;
//create an object called "outFile" of type ofstream (output file stream)
// arg #1 - path and file name
// arg #2 - constant that represents how we want to work with file (output stream in this case)
std::ofstream outFile("/home/creator/Desktop/creation.txt", std::ios::out);

//get user to enter 5 numbers:
int userGrade;
for(int i = 0; i < 2; i++)
{
    std::cout << "Enter grade number " << (i+1) << ": ";
    std::cin >> userGrade; //collect a grade from the user
    outFile << userGrade << std::endl; //write data to file (each number on it's own line)
}

outFile.close();//close the stream
std::cout << "All is well and good - file is created and data is populated" << std::endl;

//****************PART #2 - READ & MUNIPILATE DATA FROM FILE*****************************************
std::cout << "\nNext, lets read the data from the file we created." << std::endl;
std::cout << "please enter the path to the file: (ex: /home/creator/Desktop/creation.txt)" << std::endl;
std::string fileName; //the path to the file we want to read.
std::getline(std::cin, fileName);//<<< THIS IS MY QUESTION/PROBLEM
std::ifstream inFile(fileName.c_str(), std::ios::in);

if(!inFile)
{
    std::cout << "File not found!" << std::endl;
    exit(1);
}

double grade = 0;//this holds the data we retrieve from file
double total = 0; //get the sum of all the grades as a total
double average = 0; //get the average of all the grades
int numberOfGrades = 0; //number of grade values in file

//retreive and munipilate the data from the file.
while(!inFile.eof())
{
    inFile >> grade;
    total = total + grade;
    numberOfGrades++;
    std::cout << grade << std::endl;
}

average = total / numberOfGrades;
std::cout << "The average of the grades in the file is: " << average << std::endl;
inFile.close();

return 0;
}

代码刚刚浏览时的输出图像:

问题是之前的输入循环在输入缓冲区中留下了最后一个换行符,下一次调用 std::getline 时读取为空行。

阅读成绩后,ignoring 这行的其余部分很容易解决这个问题。

来自链接参考中的示例:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

顺便提一下,不要使用 while (!inFile.eof()) { ... },它不会像您预期的那样工作。相反,在你的情况下,你应该做 while (inFile >> grade) { ... }.