strcmp not working

To be exact: error: no matching function for call to 'strcmp'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstring>

using namespace std;

int main(){
int nelts = 1000;
char strnum[nelts];
cin.getline(strnum,nelts);

int wordnum, index = 0;

while(strcmp(strnum,NULL) != 0){
    if(strcmp(strnum[index]," ") == 0)
        wordnum++;
    index++;
}

cout << wordnum;
return 0;
}


The function of this program is to print out the number of times that a space is in a given string.

So if someone types "Today is Wed", the program will print 2.
I'm working to get it to print the number of words but I'm kinda stuck in this stage.
gcc
In function ‘int main()’:
14: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]

clang
14: error: no matching function for call to 'strcmp'
 note: candidate function not viable: no known conversion from 'char' to 'const char *' for 1st argument;
you are dereferencing the array, obtaining one element, that is just one character.

And if you bother to read the warnings
8: warning: ISO C++ forbids variable length array ‘strnum’ [-Wvla]
13: warning: null argument where non-null required (argument 2) [-Wnonnull]
no idea what you think you are doing there.


> The function of this program is to print out the number of times that a space is in a given string.
Then do a loop and compare the characters
1
2
3
for(auto x: strnum)
   if(x==' ')
      ++wordnum;
Last edited on
Line 13 won't work even if it compiles. strcmp requires two null-terminated strings. You're passing it NULL. Also line 14 is bad because you're passing strnum[index] which is a char, not a char*.

I suggest that you look into using strchr() instead. This will find the first occurence of a character in a string, which is what you want.
Topic archived. No new replies allowed.