私はC ++に非常に慣れていないので、ここにかなりのコードがあるので、問題の領域に凝縮するために最善を尽くします。getline im を使用してユーザー入力を取得しようとすると、このエラーが発生します。ファイル名にスペースが含まれているとは思わないので(ファイルを作成しました)、 cin << を使用しますが、これは正常に機能しましたが、ファイルを読み取ろうとすると同じエラーが発生しました。コードは次のとおりです
// includes here
using namespace std;
//other prototypes here
string getUserDataFromFile(vector<int>&, int&, string);
int main()
{
vector<int> numbers;
numbers.reserve(50);
int numberOfElements = 0;
int number = 0;
int numToFind = 0;
int numberPosition = -1;
int useFile = 0;
string filename = "";
string fileReadMessage = "";
string output = "";
string outFilename = "";
cout << "Would you like to load the data from a file?(1 for yes 0 for no)";
cin >> useFile;
cin.ignore(INT_MAX, '\n');
//get user data for manual input
if(useFile == 0)
{
//code here for manual input(works fine)...
}
//get userdata for file input
else
{
cout << "Please Enter the file path to be opened" << endl;
//fixed after adding cin.ignore(INT_MAX, '\n');
//see next function for another problem
getline(cin, filename);
fileReadMessage = getUserDataFromFile(numbers, numToFind, filename);
}
//some code to get data for output
return 0;
}
//function to get user data from file
//@param v(vector<int>&) - vector of integers.
//@param numToFind(int&) - the number we are looking for
//@param filename(string) - the filename of the file with data
//@return message(string) - a message containing errors or success.
string getUserDataFromFile(vector<int>& v, int& numToFind, string filename)
{
string message = "File Accepted";
string line = "";
int numOfElements = 0;
int count = 0;
ifstream fileToRead(filename.c_str());
//using 'cin >>' in main, the program runs till here then breaks
//if message is a file, extract message from file
if (fileToRead.is_open())
{
while (getline(fileToRead,line))
{
//code to do stuff with file contents here
}
fileToRead.close();
}
else
{
message = "Unable to open file.";
}
return message;
}
問題のある領域にいくつかのコメントを残し、問題がなかったか、テストできなかったコードのほとんどを省略しました。どんな助けでも大歓迎です。ありがとう!
したがって、私の最初の問題は cin.ignore(INT_MAX, '\n'); を追加することで修正されました。次の問題について何か推測はありますか?if (fileToRead.is_open()) 次の関数の行