2014-07-18 110 views
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) 

感谢您的帮助!

+6

你有[ *未定义的行为*](http://en.wikipedia.org/wiki/Undefined_b ehavior)在你的代码中,比较一个字符串与单个字符。与上面一行中的“strcpy”调用相同。 –

+1

你也把'strcpy'转换成'char'。 'ID'应该是一串字符串吗? –

+3

另外,为什么你在C++程序中使用C风格的字符串,其中你已经在使用C++'std :: string'类来处理一些变量? –

回答

1

也有一些是错误的代码,您声明char ID[11];的11个字符数组,在循环,其中计数从0到25的分配去ID [计数](时数为12,你正在阅读从文件中的12个ID,你会写无效的内存ID [?12])

的代码应该是:

char ID[11]; 
... 
strcpy(ID,line.substr(0,found).c_str()); //stores ID from the start of a line until a ":" is found 

假设没有ID的大小为> 11

+0

谢谢@NetVipeC - 我输入了有关ID数组的错误信息,但你已经明确了这一点。谢谢! – rselvak6