Ramsay
Ramsay

Reputation: 3

I have entered a word in character array and want to find out the length of the word

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cmath>
using namespace std;

int main(){
    
    
    char arr[100]="apple";
    int i=0;
    
    while(arr[i]!='/0'){
        i++;
    }
    
    cout<<i;
    return 0;
}

After running it I didn't get output. What's the mistake? I have just started C++.

Upvotes: 0

Views: 51

Answers (1)

Jonathan Willianto
Jonathan Willianto

Reputation: 93

The null character is denoted by a backslash not a slash. I am guessing that in your case, you get an infinite loop. '/0' is a multicharacter literal while '\0' is the null character. In your case, the correct code will be the following :

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cmath>
using namespace std;

int main(){
    
    
    char arr[100]="apple";
    int i=0;
    
    while(arr[i]!='\0'){
        i++;
    }
    
    cout<<i;
    return 0;
}

I would suggest using strlen instead as it is faster and simpler. Nevertheless, your method is good for beginners so that you have a sense of loopings. In addition, you can think of adopting the string library in C++.

Upvotes: 2

Related Questions