+ 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

3rd Jan 2019, 6:07 AM
Jothika
Jothika - avatar
4 RĂ©ponses
+ 3
what is the meaning of strlen(str) and str[i]
3rd Jan 2019, 8:40 AM
Jothika
Jothika - avatar
+ 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/
3rd Jan 2019, 10:28 AM
Ipang
+ 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 ?
19th Jan 2019, 2:53 PM
Jothika
Jothika - avatar
+ 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; }
3rd Jan 2019, 6:31 AM
Mensch
Mensch - avatar