Using 'isspace' to ignore spaces while counting characters

I cannot get this right, I am trying to use 'isspace' in the following code::



char First = "This is fun";



int count = 0;

while (!isspace (First[count])

{

count++;

}



cout << count;<br>


count should give me the number of characters in the string without the spaces????




Comments

  • : I cannot get this right, I am trying to use 'isspace' in the following code:

    :

    :   char First = "This is fun";



    Should be 'char*'



    :  

    :   int count = 0;

    :   while (!isspace (First[count])



    Missing a ')'



    :   {

    :     count++;

    :  }

    :

    :  cout << count;<br>
    :

    : count should give me the number of characters in the string without the spaces????



    Your algorithm will give you the number of concecutive non-space characters at the beginning of the string.  The algorithm quits when it finds the first space character.  In the case of this example is right after the 's' in "this" - so count should be 4.



    If you want to count all the characters in the string except for space characters:



    <br>
    &nbsp;&nbsp; int len = strlen(First);<br>
    &nbsp;&nbsp; for (int i = 0; i &lt; len; ++i)<br>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (isspace (First[i])<br>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ++count;<br>


          

    Or, if your comfortable with pointers, simply:



    <br>
    &nbsp;&nbsp; for (char* p = First; *p; ++p)<br>
    &nbsp;&nbsp;&nbsp;&nbsp; if (isspace (*p))<br>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;++count;<br>




    Cheers,

    Eric


  • : I cannot get this right, I am trying to use 'isspace' in the following code::

    :

    : char First = "This is fun";

    :

    : int count = 0;

    : while (!isspace (First[count])

    : {

    : count++;

    : }

    :

    : cout << count;<br>
    :

    : count should give me the number of characters in the string without the spaces????



    No, first off, I'll just assume char First="This is fun"; is a typo or else it wouldn't even compile. That should be char First[]="This is fun"; or char *First="This is fun";, but even still that code will count how many characters there are in memory beginning at wherever First is located up to the first space.



    If First had no spaces in it it could either GPF (if you are in a 32-bit OS) or possibly go on forever, but most likely just return bogus results.



    What you want to do is check each character in the string, either using the length of the string or the null at the end to tell you when to stop, and if the character you are at is a space then increase count.



    You should be able to figure out what to change now.


Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion