【发布时间】:2018-11-09 14:39:24
【问题描述】:
我正在做一个项目,我正在为一家假餐馆编写自动计费系统。该程序应该获取包含菜单的文本文件,将其放入结构数组或向量中,显示菜单,让客户订购并打印收据。 我正在为菜单使用结构的全局向量。
这段代码就是与问题相关的所有内容。
`
#include <iostream>
#include <fstream>
#include <vector>
//there is more code to this program, but the fault occurs very soon in the program
//and none of the rest of the code has any relevance.
//also, I don't really think that the problem is with trying to input, but I don't have enough experience to rule it out.
using namespace std;
struct menuItemType
{
string menuItem; //this is the name of the item
double menuPrice; // this is the price of the item
int menuCount;
};
vector<menuItemType> menuList; //the menu can be any size so I don't know how big it will be at this point. I'm using a vector to avoid having to declare a size
// I also have 2 other functions and some extra code in main that all need to access this vector. That is why I made it global
void getData() //this function opens the text file containing the menu and tries to read in each line.
{
ifstream input;
input.open("inData.txt");
input.peek();
int i = 0;
string item;
double price;
while(!input.eof())
{
getline(input,menuList[i].menuItem); //This is the line creating the fault.
input >> menuList[i].menuPrice;
i++;
input.peek();
}
}
int main()
{
getData();
return 0;
}
`
我已经尝试调试并确定分段错误不是特定于代码 sn-p 中注释的行。每当我尝试输入向量内的结构成员时,似乎都会发生错误。我也尝试过使用cin,所以我不相信文本文件流是问题所在。
文本文件如下所示:
Bacon and eggs
1.00
Muffin
0.50
Coffee
0.90
具体来说,我的问题是:为什么尝试输入向量内的结构成员会导致分段错误,我该如何解决。
对于冗长的解释和尴尬的格式,我们深表歉意。我对堆栈溢出和 c++ 都很陌生。
【问题讨论】:
-
欢迎来到 SO :)
-
感谢 Nox,到目前为止,SO 可能是我见过的与编程相关的最有用的网站。同样对于Rathin,我阅读了链接中的问题,并且我想我理解在循环中使用
.peek()和.eof通常是不好的代码礼仪,但对于为什么以及如何解决它有点过头了. -
@Gavin 看看我的例子,设计模式将帮助您处理文件。这种方法使其更易于使用。将内容存储到一个或多个字符串、流或缓冲区中,然后在这些变量(容器)中拥有所需的所有数据后,在完成后关闭文件句柄。然后只是解析这些字符串或缓冲区的问题......解析部分是确定字符串代表什么类型的数据,然后将其转换为该类型并将其存储到您的结构或类中,然后将结构保存到向量。
标签: c++ vector struct segmentation-fault