带有存储空字符的分隔符的 getline
我正在尝试使用 getline 输入一个分隔文本文件,但是当我调试它时,它显示变量开头有一个空字符。
这仅发生在我的 tID 变量上,该变量恰好是每行的第一个变量。当我调试时,它显示为字符数组:
[0] = '' [1] = '2' [2] = '3' [3] = '4'
这是相关代码:
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);
}
以下是 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;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于
;
是getline
的分隔符,因此它不会消耗换行符。将不带显式指定分隔符的getline
调用或ignore( numeric_limits::max(), '\n' )
添加到循环末尾。这样做的好处是忽略最后一个分号之后的数据。额外诊断代码:http://ideone.com/u9omo
Because
;
is the delimiter forgetline
, it doesn't consume the newline. Add agetline
call without an explicitly specified delimiter, orignore( 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