【发布时间】:2017-03-22 21:52:24
【问题描述】:
#include <iostream>
#include <fstream>
#include <string>
struct textbook //Declare struct type
{
int ISBN;
string title;
string author;
string publisher;
int quantity;
double price;
};
// Constants
const int MAX_SIZE = 100;
// Arrays
textbook inventory[MAX_SIZE];
void readInventory()
{
// Open inventory file
ifstream inFile("inventory.txt");
// Check for error
if (inFile.fail())
{
cerr << "Error opening file" << endl;
exit(1);
}
// Loop that reads contents of file into the inventory array.
pos = 0; //position in the array
while (
inFile >> inventory[pos].ISBN
>> inventory[pos].title
>> inventory[pos].author
>> inventory[pos].publisher
>> inventory[pos].quantity
>> inventory[pos].price
)
{
pos++;
}
// Close file
inFile.close();
return;
}
你好,
我需要有关此功能的帮助。此函数的目标是从 txt 文件中读入信息并将其读入教科书的数组结构中。 文本文件本身已经按照正确的循环顺序设置。
我的问题是,对于标题部分,一本书的标题可能是多个单词,例如“我的第一本书”。我知道我必须使用 getline 将该行作为字符串输入'title' 数据类型。
我也在某处遗漏了一个 inFile.ignore() 但我不知道如何将它放入一个循环中。
【问题讨论】:
-
我们可以看一个示例 txt 文件吗?标题和作者有什么区别?
-
没有文件样本或猜测就无法回答。猜测:您可以通过读取块和
&&运算符来测试输入有效性:if (inFile >> inventory[pos].ISBN && infile.ignore() && std::getline(inFile, inventory[pos].title) &&...)但最好将所有内容读取为strings 和getline,然后根据需要将strings 转换为数字事实。 -
inventory.txt 文件:20451 我的第一本书 Mark Lusk Pearson Publishing 40 45.34 9780316 Brown Family Mason Victor Little Brown 36 105.99 1349877 Story of My Life Norah M Jones CreateSpace 独立出版平台 20 18
标签: c++ arrays loops struct fstream