[英]c_str() seems to eliminate some integers in converting from C++ string class
I am having difficulty converting a string I am reading from a file into an integer. 我在将从文件中读取的字符串转换为整数时遇到困难。
The output of my code below is: 我的代码如下所示:
Line Raw: 118
Line C:
Elem: 0
Line Raw: 121
Line C:
Elem: 0
Line Raw: 32
Line C: 32
Elem: 32
Any idea why converting to c_string seems to eliminate some integers? 知道为什么转换为c_string似乎消除了一些整数吗?
The actual code that is causing this is below: 导致这种情况的实际代码如下:
vector<int> compressed;
string encodedLine;
while (getline(inputFile, encodedLine)) {
cout << "Line Raw: " << encodedLine << endl;
cout << "Line C: " << encodedLine.c_str() << endl;
int elem = atoi(encodedLine.c_str());
cout << "Elem: " << elem << endl;
compressed.push_back(elem);
}
The dump of the input file: 输入文件的转储:
118
121
32
UPDATE: Thanks for all the quick answers! 更新:感谢您的所有快速解答! The problem was indeed the NULL character in the file.
问题确实是文件中的NULL字符。 I noticed that the string 118 was showing as length 4. After doing the HexDump, I saw "00 31 31 38" and that confirmed this.
我注意到字符串118显示为长度4。完成HexDump之后,我看到“ 00 31 31 38”,并确认了这一点。 Thanks!
谢谢!
Any suggestions for how to write to the file (which I control in another class in the program) without prepending NULL? 在不加NULL的情况下如何写入文件(由我在程序的另一个类中控制)的任何建议?
The problem is not in the standard library (what a surprise) nor in this piece of code (a somewhat smaller surprise). 问题不在标准库中(令人惊讶),也不在这段代码中(有点小惊喜)。 It works perfectly:
它完美地工作:
I suspect that your input file has null characters in it. 我怀疑您的输入文件中包含空字符。
std:string
has no problem holding a null character, but the C string functions treat it as the end of a string, of course. std:string
拥有空字符没有问题,但是C字符串函数当然会将其视为字符串的结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.