0
我對C++很陌生,這裏有很多代碼,所以我會盡我所能將它凝聚到問題區域。當我嘗試使用getline獲取用戶輸入時,我得到這個錯誤。由於我不希望文件名稱中的空格(我創建了這些文件),我使用了cin < <,這些文件工作正常,但在嘗試讀取文件時遇到了同樣的錯誤。代碼如下std :: out_of_range在getline的內存位置錯誤
// 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')修復的;對下一個問題有什麼猜測?其在未來的功能
更好的是'cin.ignore(INT_MAX,'\ n');'它會忽略同一行上的所有未決輸入。您的版本忽略了可能不夠的單個字符。 – john
非常感謝!第二個問題的任何線索? – Bryan