我正在尝试使用 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;
最佳答案
因为 ;
是 getline
的分隔符,它不消耗换行符。添加 getline
调用时没有明确指定的分隔符,或 ignore( numeric_limits<streamsize>::max(), '\n' )
到循环结束。这具有忽略最后一个分号后的数据的“好处”。
奖金诊断代码:http://ideone.com/u9omo
关于c++ - 带有分隔符的 getline 存储一个空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5628460/