How to find spaces and store in a variable?

advertisements

In this program, I am trying to find the white space of my array, and store that value into a variable then print out that variable. The only function I know to use is the isspace one, and when I used it the error I recieve is: 'isspace' : cannot convert parameter 1 from 'char [80]' to 'int'

Any help would be greatly appreciated!

// Zachary Law Strings.cpp

#include <iostream>
using namespace std;
#include <string>
#include <iomanip>

int main()
{   int x, i,y;
char name[] = "Please enter your name: ";
char answer1 [80];
i=0;
y=0;

cout << name;
cin.getline(answer1, 79);
cout << endl;

x=strlen(answer1);

 for (int i = 0; i < x; i++){
    cout << answer1[i] << endl;
    if (isspace(answer1))
    {y=y+1;}}

 cout << endl << endl;
 cout << setw(80) << answer1;

 cout <<y;

return 0;}


Each narrow character classification function takes an int argument that is either non-negative or the special value EOF. Otherwise the behavior is undefined. And with most C++ implementations char is a signed type, so that sufficiently high values (in effect, all characters outside ASCII) become negative.

So cast the argument to unsigned char, after adding the relevant indexing,

if( isspace( (unsigned char) answer1[i] ) )

Then the resulting non-negative value will be implicitly converted to int.


Instead of placing a cast in every invocation of a classification function, consider wrapping them in more C++-friendly fashion, e.g.

auto is_space( char const c )
    -> bool
{ return ::isspace( (unsigned char) c ); }