-2

I'd like to know how to detect the number of spaces within the line that is entered by the user? The scanf function that I am using is:

scanf (" %[^\n]s", &line[0])

Here line is my char variable.

Am I doing any mistake?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115

3 Answers3

0

This is how you could count the spaces, given that you manage to successfully read the input:

uint spaces = 0;
size_t len = strlen(line);
for (size_t idx=0; idx<len; ++idx)
   if (line[idx] == ' ')
      ++spaces;

And BTW, take a look at these threads:

Max string length using scanf -> ANSI C

How to use sscanf correctly and safely

scanf is not your best buddy

Community
  • 1
  • 1
asalic
  • 949
  • 4
  • 10
0
int countspaces(const char *str)
{
  int count = 0 ;
  char c ;
  while((c = *str++) != 0)
  {
    if (c == ' ')
      count++ ;
  }

  return count ;
}

...
scanf (" %[^\n]s", &line[0])
int nbofspaces = countspaces(line) ;
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
0

Following program will print the number of spaces in a string.

    #include<stdio.h>
    void main(void)
    {
        char *input_string;
        unsigned int space_counter = 0;
        scanf("%[^\n]",input_string);
        while(input_string != '\0')
        {
           if(*input_string == ' ')//check whether the char is space
              space_counter++      //increment space counter

           input_string++;         //increment counter
        }
        printf("Number of spaces in the string=%d",space_counter);
    }
Nanobrains
  • 275
  • 1
  • 3
  • 11