Getline with a blank separator

I am trying to enter a separating text file using getline, but when I debug it, it shows me that there is an empty character at the beginning of the variable.

This only happens with my tID variable, which is the first on every line. When I debug it shows this as an array of characters:

[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; 
+4
source share
1 answer

Since ; is a separator for getline , it does not use a new line. Add a getline call without an explicit separator or ignore( numeric_limits<streamsize>::max(), '\n' ) at the end of the loop. This has the β€œbonus” of ignoring data after the last semicolon.

Bonus Diagnostic Code: http://ideone.com/u9omo

+4
source

Source: https://habr.com/ru/post/1347642/


All Articles