1

My function should list all the elements of the char array on the screen. But it should stop if the array is finished. The size of the arrays are variable. I thought that the array is terminated by '\0'. So I did this:

for(int i=0; i< size; i++){
    if(word[i] != '\0')
        cout<< word[i];
}

But the program doesn't stop there. It creates some random symbol.

E.g. char number[]= "0123"
The program gives: 0123§&

What is wrong with my if-condition?

user0042
  • 7,917
  • 3
  • 24
  • 39
lucau
  • 21
  • 3

1 Answers1

5

The problem is that your code won't stop when it encounters '\0', it just doesnt print the '\0' and continues on.

Try changing your for loop condition

for(int i=0; word[i] != '\0'; i++){
    cout<< word[i];
}

And if you just want to just print it, a simple

cout<<word;

would have sufficed

Arun A S
  • 6,421
  • 4
  • 29
  • 43
  • 1
    Nice use of loop limits instead of an `if` statement. – Matt Dec 11 '17 at 18:42
  • @lucau glad that it helped. If you are learning c++ then do look into `std::string` as suggested by the others, it will be much more useful than character arrays – Arun A S Dec 11 '17 at 18:49