Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How to count every 'space' in an inputted string? (C)

0 votes
asked Sep 22, 2018 by Dan A.P (120 points)

Newish to C programming. Was given an assignment that reads "Take in a string from the user that is at most 100 characters long.  Count how many space characters ' ' are within the string.". I actually want to understand this, but I have had no luck. A lot of the answers I could find online give solutions that include adding a new directory, but for the purposes of this class i'll have to stick with <stdio.h> and <stdlib.h>.


So far, my first thought was to create an array. 

#include <stdio.h>
#include <stdlib.h>

int main (void){

    int counter = 0, x = 0;
    char myArray[1][100];

    scanf("%s", &myArray[0]);

    while (x <= 100){
        if (myArray[0][x] = ' '){
printf("You have %i spaces within the string", counter);

Although after compiling (It only compiles through online IDEs, on Visual Studio this always fails to compile), i notice that the print statement always displays "You have 101 spaces within the string". I'm probably thinking about this wrong, in fact he hasn't shown us any example of this sort, just kinda left us to search this up ourselves. Please explain this to me, I don't want only the answer. I want to understand this. Even just a hint would be great!

1 Answer

0 votes
answered Sep 22, 2018 by jay

Your condition will always be true.
if (myArray[0][x] = ' '){

Because you have used assignment operator instead of logical equality operator. 

commented Sep 23, 2018 by Dan A.P (120 points)
Oh i forgot about that haha. Although I'm getting an error now that says "Empty character constant". I changed it to 'h', but the character is only counted when not separated by a space. For example, typing in "hhhh" will display "You have 4 spaces within the string", while typing "h h h h" will display "You have 1 spaces within the string". How do I go about fixing this?
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.