我很难将从文件中读取的字符串转换为整数。
我的代码输出如下:
Line Raw: 118
Line C:
Elem: 0
Line Raw: 121
Line C:
Elem: 0
Line Raw: 32
Line C: 32
Elem: 32
知道为什么转换为 c_string 似乎消除了一些整数吗?
导致此问题的实际代码如下:
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);
}
输入文件的转储:
118
121
32
更新: 感谢所有快速回答!问题确实是文件中的 NULL 字符。我注意到字符串 118 显示为长度 4。在执行 HexDump 之后,我看到“00 31 31 38”并证实了这一点。谢谢!
关于如何在不添加 NULL 的情况下写入文件(我在程序的另一个类中控制)的任何建议?