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?
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?
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
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) ;
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);
}