std::out_of_range 在 getline 的内存位置错误
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, '' 来解决; 对下一个问题有什么猜测吗? 这是下一个函数中的 if (fileToRead.is_open()) 行
添加
cin.ignore();
以前:
getline(cin, filename);
否则,输入后键入的 ENTER useFile
将被读入filename
。
相关文章:
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 如何在不等待检索的情况下获取C++中的内存位置?
- 向量的内存位置不连续
- 如何根据C++在同一内存位置重新初始化 C# 中的对象(还是自动完成)?
- 常量引用的内存位置
- C++强制变量到一个固定的内存位置
- 为什么未初始化的内存位置的值给出 -842150451 的值?
- 为什么存储在内存位置的值会发生变化?
- 在特定内存位置构造 c++ 对象
- 如果不初始化结构中的向量,它会自动为空还是具有随机内存位置的值?
- 内存位置出现Microsoft C++异常:std::out_of_range
- 函数,返回变量c++占用的内存位置的大小
- 无法在 Opencv 中显示图像导致内存位置
- 从十六进制到双的转换始终导致内存位置的 std::out_of_range
- 错误 在测试.exe 0x76C9FD62时出现未经处理的异常:Microsoft C++异常:内存位置0x006FF8
- 错误:内存位置的 std::length_error
- C++不同内存位置中的默认数组值
- 为什么动态分配的两个变量的内存位置不是连续的?
- Boost.进程间内存位置
- 查找编译时构造类的内存位置