簡體   English   中英

getline的內存位置錯誤處的std :: out_of_range

[英]std::out_of_range at memory location error at getline

我對C ++很陌生,這里有很多代碼,所以我將盡我所能將其壓縮到問題區域。 當我嘗試使用getline獲取用戶輸入時,出現此錯誤。 由於我不希望文件名中有空格(我制作了文件),因此我使用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())所在的行

cin.ignore();

之前:

getline(cin, filename);

否則,您輸入useFile后鍵入的useFile將被讀入filename

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM