Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

295
Visualizações
How to input an empty string in c from command prompt

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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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';
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda