+ 2
Cpp
#include <iostream> using namespace std; int main() { int n=1; char str[100]; cout<<"Enter line:"; cin.getline(str,100); for(int i=1;str[i]!='\0';i++) { if(str[i-1]!=' '&& str[i]==' ') n=n+1; } cout<<"\nNumber of words="<<n; return 0; } Pls can u explain me this program
4 Answers
+ 3
what is the meaning of strlen(str)
and str[i]
+ 3
The [] here is the subscript operator, used to point out, by index, which character is being referred to. For example, if we have a string variable named <s>, containing "SoloLearn" then the s[0] refers to the first character 'S', the s[4] refers to the fifth character 'L', remember index starts from zero.
Pictorially:
index |0|1|2|3|4|5|6|7|8|
char S o l o L e a r n
https://en.m.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B
(Look under the "Member and pointer operators")
strlen (short for 'string length') is a function that returns a value indicating how many characters there is in a string, in the case of string containing "SoloLearn", strlen returns 9, because there are 9 characters in the string.
http://www.cplusplus.com/reference/cstring/strlen/
+ 2
*** thanks
Viking tq
Ipang tq
is the calculation like this
i=1;
str[1]!=â\0â
str[1-1]!=â â && str[1]==â â
so here 0 is equal to â â(space) and
1 is not equal to â â (space)
it is false so what will it print
if my calculation is wrong pls someone xplain me
can also someone say me the meaning of str[i-1]!=â â
what does â â mean ?
+ 1
C style arrays end with a '\0' terminating character which you used as a condition on the for loop to evaluate how long it would run..Inside the loop you made sure that the char to the left and right weren't spaces thus you got the number of words entered by the user..
cin.getline(str,100) gets a string from the user...
Here's a better alternative..
#include <iostream>
#include <cctype>
using namespace std;
int main(){
int n=1;
char str[100];
cout<<"Enter line: ";
cin.getline(str,100);
for (int i=0;i<strlen(str);i++){
if(isspace(str[i]){
countinue;
}
n++;
}
cout<<"\nNumber of words="<<n;
return 0;
}