Capture is injected as input (for int and char variables)

Suppose I have a structure called books

with string and internal variables .

I want to do the following:

  • Print out the actual value stored in the variable.
  • Give an opportunity to insert a new value.
  • If the user presses 'Enter', the value remains unchanged.

I tried to do it with scanf

, but it can't get empty input. If that were the case, I could simply do:

printf("Current value: %d     New value: ",books.intVar);
scanf("%d",aux);
if (aux) {
     books.intVar = aux;
}

      

And something similar to strings, but using a function strcpy()

to assign a new value.

I'm sure the solution to this problem is a combination of gets()

and sscanf()

, but I can't see how to use them to get the result I'm looking for.

Appreciate any help.

+3


source to share


3 answers


Instead, you can use fgets()

like this

char line[100];
int  value;
if (fgets(line, sizeof(line), stdin) != NULL)
 {
    if (line[0] == '\n')
        handleEmptyLine();
    else
     {
        value = strtol(line, NULL, 10);
        fprintf(stdout, "New Value: %d\n", value);
        /* Do whatever you want with value */
     }
  }

      

While the same code probably works with gets()

, this is a very bad and unnecessary thing because you run the risk of a buffer overflow with a help gets()

that has no way of limiting the input length, but fgets()

allows you to set the maximum value for the destination buffer length.



You should notice that you are fgets()

reading a character '\n'

at the end of the input, which you can conveniently use in your case to check if the string is empty, although this is not enough, since an empty string can also be a bunch of spaces, so the test line[0] == '\n'

will only work if the user clicks the Enter/ key Return, so it would be safer to do something like

char  buffer[100];
char *line;
int   value;

if ((line = fgets(buffer, sizeof(buffer), stdin)) != NULL)
 {
    while ((line[0] != '\0') && (isspace((int) line[0]) != 0))
        line++;
    if (line[0] == '\0')
        handleEmptyLine();        
    else
     {
        value = strtol(line, NULL, 10);
        fprintf(stdout, "New Value: %d\n", value);
        /* Do whatever you want with value */
     }
  }

      

+2


source


Use fgets()

instead scanf()

. And if you want to record empty input, you can compare it with '\n'

.



0


source


I just found a much shorter and easier way to do the same as @iharob did:

char aux[100];

// Sample data:
char name[100];
int number = 250;
strcpy(name,"Sample name");

// Interger case:
gets(aux);
sscanf(aux,"%d",number);

// String case:
gets(aux);
sscanf(aux,"%s",name);

      

When the program asks for an int or a string, and we do not provide it (instead of pressing Enter), the value of variables number

and name

will not change.

0


source







All Articles