从文件 c++ 中的下一行读取
Reading from the next line in a file c++
我正在尝试制作一个库存系统,该系统从列表中读取并将内容存储在并行向量中。我的向量在我包含在代码中的类中设置为公共成员。文本文件如下所示
1111
Dish Washer
20 250.50 550.50
2222
Micro Wave
75 150.00 400.00
3333
Cooking Range
50 450.00 850.00
4444
Circular Saw
150 45.00 125.00
6236
Tacos
200 5.00 5.50
这是我的代码
int main()
{
char choice;
Inventory Stocksheet(5); // the included list has 5 items if a text file has more then it should scale fine
int id, ordered;
string name;
double manuprice, price;
ifstream data;
data.open("Inventory Data.txt");
if (data.fail())
{
cout << "Data sheet failed to open n";
exit(1);
}
while (data >> id )
{
Stocksheet.itemID.push_back(id);
getline(data,name);
Stocksheet.itemName.push_back(name); // this is where my code fails
data >> ordered;
Stocksheet.pOrdered.push_back(ordered);
Stocksheet.pInstore.push_back(ordered);
data >> manuprice;
Stocksheet.manuPrice.push_back(manuprice);
data >> price;
Stocksheet.sellingPrice.push_back(price);
}
do
{
cout << " Your friendly neighborhood tool shackn";
cout << "Select from the following options to proceed n";
cout << "1. Check for item n";
cout << "2. Sell an iem n";
cout << "3. Print Report n";
cout << "Input any number other than 1,2 or 3 to exit n";
cout << "Selection : ";
cin >> choice; // think about sstream here
switch (choice)
{
case '1': checkforitem(Stocksheet);
break;
case '2': sellanitem(Stocksheet);
break;
case '3': printthereport(Stocksheet);
break;
default: cout << " ^-^ Exiting the shop. Have a fantastic day! ^-^ n";
break;
}
}while ((choice == '1') || (choice == '2') || (choice == '3'));
data.close();
return 0;
}
我评论了我的代码中断的地方。在 while 循环中,数字 id 被推送到我的第一个向量,但名称为空,之后的每个值都留空。我的循环设置方式有问题吗?
当你使用>>
运算符时,你会得到一个"word"类型的东西。它停止在空白处。因此,当您调用 getline
时,它会读取第一行末尾的换行符(上面有 id)并停止。所以你的name
是空白的。
您可以在切换到getline
之前调用data.ignore()
,这将处理换行符。小心将>>
运算符与getline
混合。它没有达到您的期望。
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 如何从一行中读取特定数量的字符?(C++)
- 读取最后一行代码算法 - c++ 时出现问题
- 而(!inputfile.eof())只读取第一行?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 需要从存档中读取一行文本.txt直到找到"hhh",然后转到下一行
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 从文件中的一行读取特定数据-C++
- 使用std::getline()读取一行
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 从文件读取并在一行中写入 cout
- 将 ifstream 文件和每一行读取到数组中
- 从文件 c++ 中的下一行读取
- 在同一行读取具有多个类型的文件
- 写入终端并从同一行读取
- 如何在c++中从最后一行读取文本文件
- 逐行读取数组,每一行读取3个值
- 在同一行读取字符串和整数
- 从一行读取hh:mm格式的时间