コードを 2 つの個別のプログラムに分割すると、希望どおりに動作します (ファイルを作成する部分 #1 と、ユーザーとしてファイルにアクセスしようとする部分 #2 を分離します)。しかし、コードを 1 つのプログラム (以下を参照) に入れるとすぐに、getline() メソッドを使用して標準入力から入力を収集することができなくなります。プログラムは、getline メソッドがソース コードにあるポイントでユーザー入力を収集するために停止することなく、最後まで進みます。
私はたくさんの回答された質問を読み、次のことを無駄にしようとしました:
- タイピング
#include <string>
- タイピング
outFile.clear();
- タイピング
inFile.clear();
- コードの一部をコメントアウトして、問題を特定できるかどうかを確認するなど、過去 3 時間で他のことを試しました。
このプログラムの目的は、テキスト ファイルを作成し、「教師」から 2 つの成績を取得してテキスト ファイルに入れることです。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;
}
コードが実行されたときの出力の画像: