带有存储空字符的分隔符的 getline

发布于 2024-10-31 10:05:41 字数 1029 浏览 5 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

向地狱狂奔 2024-11-07 10:05:41

由于 ;getline 的分隔符,因此它不会消耗换行符。将不带显式指定分隔符的 getline 调用或 ignore( numeric_limits::max(), '\n' ) 添加到循环末尾。这样做的好处是忽略最后一个分号之后的数据。

额外诊断代码:http://ideone.com/u9omo

Because ; is the delimiter for getline, it doesn't consume the newline. Add a getline call without an explicitly specified delimiter, or ignore( 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文