使用分隔符存储空字符的Getline

getline with delimiter storing an empty character

本文关键字:字符 Getline 存储 分隔符      更新时间:2023-10-16

我试图用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