Reputation: 3
#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
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