【问题标题】:std::out_of_range at memory location error at getlinestd::out_of_range 在 getline 的内存位置错误
【发布时间】:2013-10-01 05:56:18
【问题描述】:

我对 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;
}

我在问题区域留下了几个 cmets,并遗漏了大部分我没有遇到问题或无法测试的代码。任何帮助表示赞赏。谢谢!

所以我的第一个问题是通过添加 cin.ignore(INT_MAX, '\n');对下一个问题有任何猜测吗?它是下一个函数中的 if (fileToRead.is_open()) 行

【问题讨论】:

    标签: c++ visual-c++ ifstream getline


    【解决方案1】:

    添加

    cin.ignore();
    

    之前:

    getline(cin, filename);
    

    否则,您在输入useFile 后输入的ENTER 将被读入filename

    【讨论】:

    • 更好的是cin.ignore(INT_MAX, '\n');,它会忽略同一行上的所有待处理输入。您的版本忽略了可能不够的单个字符。
    • 非常感谢!关于第二个问题的任何线索?
    猜你喜欢
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多