Ali
Ali

Reputation: 10463

Why there is an extra data being store in the array?

I'm trying to program a code in C++ for my assignment.

What happen is one of the part where I have to accept some data from my main and in my function I have to get first part of the array that sent by main and put in my array in the function.

        for (int i = 0; i <= strlen(main) && exit == 0; i++){
        if (main[i] != ';' || main[i] != '\0'){

        keyword[i] = data[i];
        if(main[i] == ';' || main[i] == '\0')
        exit = 1;

        }

This is the code in the array named main = "Hello World;Yes;No;Okay;Good Bye",

So what happen is I want to store that Hello World in my array called keyword and the problem is once I printf the keyword string I see extra data after the word Hello World

Here is what I have on the printf

Your keyword-----> 'Hello World;? ' Actual keyword---> 'Hello World'

Is there any problem with my logic use above??

Thanks

Upvotes: 0

Views: 86

Answers (3)

Mahesh
Mahesh

Reputation: 34625

i <= strlen(main) needs to i < strlen(main) and there is no need for the extra termination character check in the if. Also make sure that keyword is null terminated (\0) after copying the necessary data.

Just to get you idea, assuming the destination is big enough to hold the data being copied.

for (int i = 0; i < strlen(main) ; i++)
    if (main[i] != ';'){
        keyword[i] = data[i];  // Copy the characters until `;` isn't found
    } else {
        keyword[i] = '\0' ;   // If `;` found, null terminate the copied destination.
        break;
    }
}

Upvotes: 2

Lefteris
Lefteris

Reputation: 3256

The extra data you see is probably the null termination character. Note that you are using

i <= strlen(main)

So this actually prints all the characters plus the null termination. You should change it to

i < strlen(main)

Generally in order to better understand what you do, a bit more code would really be helpfull.

But as begemoth said it appears that for what you want to do your if() test should be:

 if(main[i] != ';' && main[i] != '\0')

Upvotes: 1

Begemoth
Begemoth

Reputation: 1389

The condition

if (main[i] != ';' || main[i] != '\0')

is always true, you want to test if the character is neither ';' nor '\0', so need to connect the test with the && operator (and) not || (or).

Some notes:

  1. the strlen function has O(N) complexity it is better to call it once before the loop to determine the length of the string or replace the test with *main[i].

  2. The exit variable is redundant, use break.

Upvotes: 1

Related Questions