Condition for entering an empty string in c

If the user enters an empty name string, the loop should break.

void Put_txt(void){
FILE *f;
f = fopen("table.txt", "wt");
char name[255];
int num;
int value;
while(name == /*???*/){
scanf("%s",name);
scanf("%d", &num);
scanf("%d", &value);
fprintf(f,"%s", name);
fprintf(f,"\t%d",num);
fprintf(f,"\t%d\n",value);
}
fclose(f);

}

Author: Orizz, 2018-11-17

2 answers

"Enters " where and how? First, you are checking a string that is not initialized at all. Secondly, the function scanf, which you use next, in principle does not allow you to "enter an empty string". The formatted input functions of the scanf group in the standard C library either read a non-empty sequence of data, or fail without reading anything at all.

If you want to give the user the option to "enter an empty string", use the function fgets and check the result for equality to the string "\n"

do 
{
  char name[255];
  if (fgets(name, sizeof name, stdin) == NULL)
    break;
  if (strcmp(name, "\n") == 0)
    break;
  ...
} while (1); 

Just keep in mind that mixing formatted and unformatted input has its own characteristics. Your scanf will leave in the input buffer the newline characters that the above fgets will be interpreted as "entering an empty string", and will result in the end of the loop. Between scanf and fgets, the input buffer must be cleaned. And it is better not to mix formatted and unformatted input at all.

 0
Author: AnT, 2018-11-17 18:39:09

Maybe

while(strlen(name) == 0)
 0
Author: Игорь, 2018-11-17 19:56:01