【发布时间】:2020-07-27 07:28:08
【问题描述】:
我的主程序中有这段代码。 我不知道我的文本文件应该格式化成什么方式让我的主getline从中获取。
//...
BOOK_TYPE book[100];
int index = -1, choice;
input.getline(book[++index].isbn, 14);
while (input)
{
input.getline(book[index].author, 20);
input.getline(book[index].title, 30);
input.getline(book[index].publisher, 20);
input.getline(book[index].year, 5);
input.getline(book[index].price, 10);
input.getline(book[index].quantity, 103);
for (int k = 0; k < 5; k++)
{
input.getline(book[index].category[k].cor_x, 2);
input.getline(book[index].category[k].cor_y, 2);
input.getline(book[index].category[k].genre, 20);
}
// clear unwanted whitespace
if (input.peek() == '\n')
input.ignore(256, '\n');
// read next number
input.getline(book[++index].isbn, 14);
}
input.close();
//...
假设我有这个书单:
9780809875214,John Wick,The assasinate of a Gang,Tree Production,2014,39.00,4,2,2
9788373191723,J.R.R Tolkien,The Lord of the Rings,Allen & Unwin,1954,120.45,6,3,1
9783791535661,Lewis Carroll, Alice's Adventure in Wonderland,Macmillan Publishers,1865,100.25,5,3,2
9781517322977,Mikhail Bulgakov,The Master and Margartia,Penguin Books,1967,125.00,7,3,3
9780676516197,Vladmir Nabokov,Lolita,Olympia Press,1955,98.25,3,3,1
9781095627242,Anna Sewell,Black Beauty,The Jarrold Group,1877,60.25,2,3,2
9788497592581,Umberto Eco,The Name of the Rose,Bompiani,1980,45.65,7,1,3
9780062316110,Harari and Yuval Noah,Sapiens: A Brief History of Humankind,Harper Perennial,2018,18.06,2,1,3
我想知道应该在哪里间隔,输入下一行等等,以便我的文件可以逐行读取,并在用户选择时作为书单输出给用户。
【问题讨论】:
-
您拥有的是一个Comma-Separated Values (or CSV) 文件。您可以使用
std::getline首先将整行读入一个字符串,然后再次对其进行标记。 (也可以使用istream::getline完成,但请不要使用它)。或者你可以找到一个为你做这件事的图书馆(这真的是我推荐的,除非它是作业的一部分)。重要的部分是不要忘记 分隔符。 -
@Someprogrammerdude 我在一个结构文件中有不同的数组,如果我把整行变成一个字符串,它如何被分成不同的数组?