Reputation: 95
I am trying to input a delimited text file with getline but when I debug it it shows me that there is an empty character at the beginning of the variable.
This is only happening with my tID variable which happens to be the first on each line. When I debug it shows this as the character array:
[0] = '' [1] = '2' [2] = '3' [3] = '4'
Here is the relevant code:
ifstream inFile("books.txt");
if (!inFile){
cout << "File couldn't be opened." << endl;
return;
}
while(!inFile.eof()){
string tID, tTitle, tAuthor, tPublisher, tYear, tIsChecked;
getline(inFile,tID, ';');
getline(inFile,tTitle, ';');
getline(inFile,tAuthor, ';');
getline(inFile,tPublisher, ';');
getline(inFile,tYear, ';');
getline(inFile,tIsChecked, ';');
library.addBook(tID, tTitle, tAuthor, tPublisher, tYear, (tIsChecked == "0") ? false : true);
}
Here are a few lines of book.txt:
123;C++ Primer Plus; Steven Prata; SAMS; 1998;0;
234;Data Structures and Algoriths; Adam Drozdek; Course Technlogy; 2005;0;
345;The Art of Public Speaking; Steven Lucas;McGraw-Hill;2009;0;
456;The Security Risk Assessment Handbook; Douglas J. Landall;Auerbach;2006;1;
Upvotes: 4
Views: 5017
Reputation: 137780
Because ;
is the delimiter for getline
, it doesn't consume the newline. Add a getline
call without an explicitly specified delimiter, or ignore( numeric_limits<streamsize>::max(), '\n' )
to the end of the loop. This has the "bonus" of ignoring data after the last semicolon.
Bonus diagnostic code: http://ideone.com/u9omo
Upvotes: 4