Visual Studio从文件中填充数组时中断
Visual Studio aborts when filling array from file
我正在尝试将库存系统读取到结构数组中。当我调用该函数并进入第一行时,我尝试将数据写入数组中,我得到了错误:
实验室中的0x77777CA932在09.exe中未经处理的异常:Microsoft C 例外:std :: out_of_range在内存位置0x00f3dc68。
这是结构:
struct inventory {
int record;
string toolname;
int quantity;
double cost;
};
数组声明:
inventory unsortedArray[100];
这是函数(假设文件的第一行是83 #Electric Sander#7 57.00(:
void fillArray(inventory unsortedArray[]) {
ifstream file;
string line;
string delim = "#";
stringstream ss;
file.open("records.txt");
int i = 0;
while (!file.eof()) {
getline(file, line);
unsigned first = line.find_first_of(delim);
unsigned last = line.find_last_of(delim);
unsortedArray[i].toolname = line.substr(first, (last - first) + 1);
line.erase(first, (last - first) + 1);
ss << line;
ss >> unsortedArray[i].record;
ss >> unsortedArray[i].quantity;
ss >> unsortedArray[i].cost;
i++;
}
file.close();
}
问题1
使用
while (!file.eof())
通常会导致问题。查看为什么iostream :: eof内部被认为是错误的?
问题2
使用正确的类型捕获std::string::find_first_of
和std::string::find_last_of
的返回值。
使用
auto first = line.find_first_of(delim);
auto last = line.find_last_of(delim);
或
std::string::size_type first = line.find_first_of(delim);
std::string::size_type last = line.find_last_of(delim);
问题3
在进行使用之前,请务必检查std::string::find_first_of
和std::string::find_last_of
的返回值。
auto first = line.find_first_of(delim);
auto last = line.find_last_of(delim);
if ( first == std::string::npos )
{
// Didn't find it. Figure out what to do.
}
if ( last == std::string::npos )
{
// Didn't find it. Figure out what to do.
}
// Both checks are done. Now you can use first and last.
我的建议
使用
while (getline(file, line)) {
unsigned first = line.find_first_of(delim);
unsigned last = line.find_last_of(delim);
if ( first == std::string::npos )
{
break;
}
if ( last == std::string::npos )
{
break;
}
unsortedArray[i].toolname = line.substr(first, (last - first) + 1);
line.erase(first, (last - first) + 1);
// Don't use ss << line
// Construct ss in the loop. You don't need to mess with its
// old state
std::istringsteram ss(line);
ss >> unsortedArray[i].record;
ss >> unsortedArray[i].quantity;
ss >> unsortedArray[i].cost;
i++;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '