我正在尝试读取一个包含标题和作者列表的文件,并且我需要能够忽略分隔文件中每一行的换行符。
例如,我的.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;
}
} 我是不是做错了什么?
发布于 2011-08-06 06:37:04
正如@Potatoswatter所说,std::getline通常会去掉换行符。如果换行符仍然有效,那么您可能正在使用一个使用\n作为换行符的系统,而您的文件中却有\r\n换行符。
只要将多余的换行符添加到字符串中,就可以将它们删除。您可以使用以下内容来实现此目的:
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::isspace)).base(), s.end());或者类似的。您可以在<algorithm>中找到std::find_if,在<clocale>中找到std::isspace,在<functional>中找到std::not1。
发布于 2011-08-07 00:23:11
这样啊,原来是这么回事!问题出在我正在读取的文件。我从讲师给我们的.txt中复制并粘贴了标题和作者的文件到一个新的.txt文件中,现在它可以很好地工作了!谢谢大家的帮助!!
https://stackoverflow.com/questions/6963247
复制相似问题