【发布时间】:2011-08-05 22:25:01
【问题描述】:
我正在尝试读取包含标题和作者列表的文件,并且我需要能够忽略分隔文件中每一行的换行符。
例如,我的 .txt 文件可能有这样的列表:
The Selfish Gene
Richard Dawkins
A Brave New World
Aldous Huxley
The Sun Also Rises
Ernest Hemingway
我必须使用并行数组来存储这些信息,然后才能像这样格式化数据:
The Selfish Gene (Richard Dawkins)
我试图使用getline 来读取数据,但是当我去格式化标题和作者时,我得到了这个:
The Selfish Gene
(Richard Dawkins
)
从文件中读取列表时如何忽略换行符?
这是我目前所拥有的:
int loadData(string pathname)
{
string bookTitle[100];
string bookAuthor[100];
ifstream inFile;
int count = -1; //count number of books
int i; //for variable
inFile.open(pathname.c_str());
{
for (i = 0; i < 100; i++)
{
if(inFile)
{
getline(inFile, bookTitle[i]);
getline(inFile, bookAuthor[i]);
count++;
}
}
inFile.close();
return count;
}
编辑:
这是我的输出函数:
void showall(int count)
{
int j; //access array up until the amount of books
for(j = 0; j < count; j++)
{
cout << bookTitle[j] << " (" << bookAuthor[j] << ")";
cout << endl;
}
}
我在这里做错了吗?
【问题讨论】:
-
getline应该去掉换行符。也许您在 UNIX 机器上使用了 DOS 文件,而回车符正在滑过并被解释为换行符? -
如果对
std::getline的调用失败,则此代码的行为会很糟糕。仅供参考。 -
你的输出代码是什么样的?
-
感谢您的回复。我将输出代码添加到问题的正文中。我正在使用 Mac,使用 Xcode 进行编译。那会有什么不同吗?