4

I have been revising my skills in the way I came to C language first to start from scratch I am working out few problems myself. In the way I am writing a program which outputs the length of the entered string the code goes like this.

#include<stdio.h>
int main()
{
    char a[100];
    int n=0;
    printf("Enter the string : ");
    scanf("%s",a);
    while(a[n]!='\0')
    n++;
    printf("length of %s is %d\n",a,n);
}

It worked. But suddenly a thought came to my mind why don't we input an empty string and check whether the output would be 0(zero). I tried pressing enter in the command prompt where I generally run my code. But it goes on asking input until and unless I entered a valid input in the sense a string with characters. But how can I enter a manual string from the command prompt does it can happen or if it will. Hope my question is answered?

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

1 Answers1

2

Thy the following

a[0] = '\0';
scanf( "%99[^\n]", a );

or

if (scanf( "%99[^\n]", a ) == 0) a[0] = '\0';

Another alternative is to use fgets. But the function can append the new line character '\n' to the input string even if the input is empty. You need to remove it like for example

#include <string.h>
#include <stdio.h>

...

fgets( a, sizeof( a ), stdin );
a[ strcspn( a, "\n" ) ] = '\0';
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Can you please explain me what exactly happens in the with the code. the '99' is for limit of characters we are taking input and '^\n' is like a expression or automata. scanf is returning 0 here. So its not possible to do it without explicitly telling a[0]='\0'; help me out – BhanuPrakashSakkuri Dec 19 '21 at 16:40
  • @BhanuPrakashSakkuri When you at once press the Enter key then nothing will be stored in the string. So you need yourself to set the terminating zero to make an empty string. These symbols ^\n means read until Enter is pressed – Vlad from Moscow Dec 19 '21 at 16:42