Reputation: 31
I am trying to read a file with a list of titles and authors, and I need to be able to ignore the newline character that separates each line in the file.
For example, my .txt file might have a list like this:
The Selfish Gene
Richard Dawkins
A Brave New World
Aldous Huxley
The Sun Also Rises
Ernest Hemingway
I have to use parallel arrays to store this info, and then be able to format the data like so:
The Selfish Gene (Richard Dawkins)
I was trying to use getline
to read the data, but when I go to format the title and author, I get this:
The Selfish Gene
(Richard Dawkins
)
How do I ignore the newline character when I read in the list from the file?
This is what I have so far:
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;
}
EDIT:
This is my output function:
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;
}
}
Am I doing something wrong here?
Upvotes: 3
Views: 8525
Reputation: 31
I GOT IT! The problem was the file that I was reading. I copy and pasted the file with the titles and authors from the .txt my instructor gave us into a new .txt file, and now it works fine the way I had it! Thank you everyone for the help!!
Upvotes: 0
Reputation: 106599
As @Potatoswatter says, std::getline
normally does strip the newline character. If newlines are still getting through, you're probably using a system which uses \n
for it's newlines, yet your file has \r\n
newlines.
Just remove the extra newlines after they get added to the string. You can do that with something like:
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::isspace)).base(), s.end());
or similar. You'll find std::find_if
in <algorithm>
, std::isspace
in <clocale>
, and std::not1
in <functional>
.
Upvotes: 2