我正在尝试读取一个包含标题和作者列表的文件,我需要能够忽略文件中分隔每一行的换行符。
例如,我的 .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;
}
}
我是不是做错了什么?
最佳答案
正如@Potatoswatter 所说,std::getline
通常会去除换行符。如果换行符仍然通过,您可能正在使用使用 \n
的系统因为它是换行符,但你的文件有 \r\n
换行符。
只需将多余的换行符添加到字符串中即可。你可以用类似的东西来做到这一点:
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::isspace)).base(), s.end());
或类似的。你会发现 std::find_if
在<algorithm>
, std::isspace
在<clocale>
, 和 std::not1
在<functional>
.
关于c++ - 以列表格式读取文件时如何忽略换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6963247/