0
所以我运行这段代码打开一个文件并比较一个本地字符与存储在文件中的值,但由于某种奇怪的原因,strcmp告诉我“15”等于“17”。 。 有什么想法吗?这很奇怪,因为该问题只发生在第17行。这里是相关的代码:strcmp比较不正确
...
string line;
size_t found;
size_t nextFound;
char ID[11];
char storage_ID[11] = "15";
//Open the file
ifstream file(FILE);
if (file.is_open())
{
for (int count = 0; count < 25; count++)
{
getline(file,line);
if (file.eof())
{
return;
}
//store object ID
found = line.find(":");
strcpy(ID[count],line.substr(0,found).c_str()); //stores ID from the start of a line until a ":" is found
if(strcmp(storage_ID,ID[count])==0)
{
foundID = true;
}
else
{
foundID = false;
}
而这里的文件是什么样子:
...
1:1234567890:101:A123B4CD
2:2234567890:102:B123B4CD
3:3234567890:103:C123B4CD
(this goes on for 20 lines)
感谢您的帮助!
你有[ *未定义的行为*](http://en.wikipedia.org/wiki/Undefined_b ehavior)在你的代码中,比较一个字符串与单个字符。与上面一行中的“strcpy”调用相同。 –
你也把'strcpy'转换成'char'。 'ID'应该是一串字符串吗? –
另外,为什么你在C++程序中使用C风格的字符串,其中你已经在使用C++'std :: string'类来处理一些变量? –