rselvak6
rselvak6

Reputation: 15

strcmp comparing incorrectly

So I was running this code to open a file and compare a local char to the values stored in the file, but for some weird reason, strcmp is telling me that "15" is equal to "17".. any thoughts? It's strange because the problem only happens at the 17th line.. Here's the relevant code:

...
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;
         }

And here's what the file looks like:

...
1:1234567890:101:A123B4CD
2:2234567890:102:B123B4CD
3:3234567890:103:C123B4CD
(this goes on for 20 lines)

Thanks for the help!

Upvotes: 0

Views: 200

Answers (1)

NetVipeC
NetVipeC

Reputation: 4432

There is something wrong in the code, you are declaring char ID[11]; an array of 11 chars, in the loop where count go from 0 to 25 your assigning to ID[count] (when count is 12, you are reading the 12 ID from the file, you will be writing to invalid memory ID[12-?])

The code should be:

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

Assuming no ID has size > 11

Upvotes: 1

Related Questions