-1

I have to make a simple function to display the number of whitespaces in a predefined array of characters. This is my code : (please ignore the first part, only last part and whitespaces function)

#include <iostream>
#include <conio.h>
using namespace std;

int whitespaces(char[]);

void main(){
    char a[] = "Array of characters for test\n";  //Simple array of characters
    cout << "\n This is a test : " << a;
    char b[] = "\n\t Another array of character for test\n"; //Simple array with some escape sequences, \t and \n
    cout << "\n This is a test for usage of escape sequences : " << b;
    char c[] = "T E S T\n";                                   //Simple array with 8 characters and whitespaces
    cout << "\n Last test for whitespaces : "<<c;
    int ws = whitespaces(c);
    cout << "\n Number of whitespaces for the last array of characters is : "<<ws;
    _getch();
}

int whitespaces(char c[]){
    int count = 0;
    for (int n = 0; n <= sizeof(c); n++) {
        if (c[n] == ' '){
            count++;
        }
    }
        return(count);
}

Using Visual Studio express

2 Answers2

3

Here's what you can use if you want all whitespace characters to be counted (not only the space character):

std::string::size_type countWs( std::string const& str )
{
    return std::count_if( std::begin(str), std::end(str),
                          [] (unsigned char c) {return std::isspace(c);} );
}

Or, alternatively,

std::size_t countWs( char const* str )
{
    std::size_t c = 0;
    while (*str)
        c += !!std::isspace((unsigned char)*str++);
    return c;
}

Demo. As to the casts to unsigned char, this question might be worth looking at.

Community
  • 1
  • 1
Columbo
  • 60,038
  • 8
  • 155
  • 203
1

You have to use standard C function std::strlen declared in header <cstring> instead of sizeof operator because an array passed by value to a function is implicitly converted to a pointer to its first element. Also the blank character is not the only white space character. Either you should use standard function std::isspace or std::isblank declared in header <cctype>

So the function will look like

#include <cstring>
#include <cctype>

//...

int whitespaces( const char c[] )
{
    int count = 0;
    size_t n = std::strlen( c );

    for ( size_t i = 0; i < n; i++ ) 
    {
        if ( std::isspace( c[i] ) ) ++count;
    }

    return ( count );
}

The other way is to use the characteristic of character arrays that store strings that they have the terminating zero.

In this case the function could be defined as

#include <cstring>
#include <cctype>

//...

int whitespaces( const char c[] )
{
    int count = 0;

    while ( *c )
    {
        if ( std::isspace( *c++ ) ) ++count;
    }

    return ( count );
}

Also take into account that there are standard algorithms std::count and std::count_if that can be used instead of your function.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335