[英]Need help reading data from .txt file into an array C++
#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(),但是我不知道如何将其放入循环。
假定输入格式为:
ISBN title author publisher price quantity price
也就是说,数据成员之间用行空格隔开,您可以为struct textbook
定义operator>>
,其外观类似于:
std::istream& operator>> (std::istream& is, textbook& t)
{
if (!is) // check input stream status
{
return is;
}
int ISBN;
std::string title;
std::string author;
std::string publisher;
int quantity;
double price;
// simple format check
if (is >> ISBN >> title >> author >> publisher >> quantity >> price)
{
// assuming you additionally define a (assignment) constructor
t = textbook(ISBN, title, author, publisher, quantity, price);
return is;
}
return is;
}
然后,只需读取文件即可:
std::ifstream ifs(...);
std::vector<textbook> books;
textbook b;
while (ifs >> b)
{
books.push_back(b);
}
关于getline()
的使用,请参见此答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.