I tried to create a program that counts the number of words in a line by comparing " " with every character from the line , counting them in a j++
But it always shows me the value 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <stdio.h>
#include <string.h>
usingnamespace std;
int main()
{int i,j=1,n; char x[10]=" ",y[20],k;
cout<<"Enter your line: "; gets(y);
n=strlen(y);
for (i=0;i<=n;i++);
{k=y[i];
if('k'=='x') j++;
}
cout <<"Your line has "<<j<<" words";
}
As k and x are variables, you shouldn't have them in quotes on line 12. With the quotes, it compares the char 'k' with the char 'x' as opposed to the actual values of the variables.
Remove the quotes on line 12, and it should work.
k is a variable, but I'm not sure what you mean to check against. You've defined x as an array, not a single char. Are you looking to see if there's a blank space, indicating a break between words?
Can you use <string> and getline?
1 2 3 4
string y;
cout<<"Enter your line: ";
getline(cin,y);
n=y.length();
Then check if k == ' ' if you mean to check for an empty space?
Also - line 10 - remove the semicolon at the end of the for statement.
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
usingnamespace std;
int main()
{
int j = 0;
char y[200] = {'\0'};
char *token = NULL;
char *delimeter = " \t\r\f\n"; //Delimeters are space, tab, carriage return, form feed and new line
cout << "Enter your line: ";
gets(y);
//get the first word until any of the delimiting characters found
token = strtok(y, delimeter);
while (token != NULL) {
j++;
//get the next word until any of the delimiting characters found
//no need to pass y in strtok, just pass NULL for the succeeding calls to strtok
token = strtok(NULL, delimeter);
}
cout << "Your line has " << j << " words" << endl;
system("pause");
}