4

我正在尝试使用 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;
4

1 回答 1

4

因为;是 的分隔符getline,所以它不消耗换行符。添加一个getline没有明确指定分隔符的调用,或者添加ignore( numeric_limits<streamsize>::max(), '\n' )到循环的末尾。这具有忽略最后一个分号之后的数据的“好处”。

奖励诊断代码:http: //ideone.com/u9omo

于 2011-04-11T22:58:05.360 回答