使用分隔符存储空字符的Getline
getline with delimiter storing an empty character
我试图用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
相关文章:
- 如何在 getline 中删除/忽略超过特定数字的字符?
- Getline(); 提取以 1A 字符停止
- 重用字符数组和 cin.getline
- 对c++中的输入使用getline函数时忽略第一个字符
- Cin 和 getline 无法正确保存非 ascii 字符
- 字符串和getline字符
- 在 std::getline() 上使用任何字符作为分隔符
- 填充字符数组的最佳方法(获取与cin.getline)
- 如何替换/忽略 C stdio.h getline() 中的无效 Unicode/UTF8 字符
- 看到' - '字符时我无法结束 getline,有人可以帮助我在 c++ 中获取 getline() ifstream
- 使用 getline() 时字符消失器
- getline删除第一个字符;删除cin.ignore();无法解决
- 使用getline,c 中的数组以相反的方式将所有字符单词转动
- 为什么cin.getline分配给字符数组,但使用'='不会?
- 类似于 istream::getline() 的东西,但带有替代的 delim 字符
- C++ cin.getline 只读取一个字符
- 如何使用嵌套的getline()函数来获取字符串中的特殊字符和标点符号
- 带有 UNIX 格式字符的 getline() 文本
- istream::getline()中有0个字符
- C++的第一个字符不会使用getline打印出来