如果我将代码分成两个单独的程序,它会像我想要的那样工作(在我创建文件的地方分隔 3 部分 #1,在我尝试以用户身份访问文件的部分 #2 中);但是一旦我将代码放入单个程序中(见下文),我就无法使用 getline() 方法从标准输入中收集输入;该程序只是在源代码中 getline 方法所在的点处不停地收集用户输入,直到结束。
我阅读了一堆已回答的问题,并尝试以下方法无济于事:
- 打字
#include <string>
- 打字
outFile.clear();
- 打字
inFile.clear();
- 我在过去 3 小时内尝试了其他方法,例如注释掉部分代码以查看是否可以查明问题。
该程序的目的是创建一个文本文件,然后从“老师”那里获得 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;
}
作为代码的输出图像刚刚穿过: