Home > other >  number and string during same input
number and string during same input

Time:03-20

hello ive got this simple program, where i need to imput a number, and 2-letter string, the string is working normally, but the number gets weird

here is the program

void main(){
int input_year=0;      
char input_string[1];
        
scanf("%d %s", &input_year, input_string);
char temp1 = input_string[0];
char temp2 = input_string[1];

printf("%d", input_year);
printf("%c", temp1);
printf("%c", temp2);
}

input used: 20200405 RD number (whitespace) String

the temp1 and temp2 are ok, and do what i expect them to do, but the input_year prints 20200192 rather than 20200405.

CodePudding user response:

You need to remember that strings in C are really called null-terminated strings. A string of even one single character need space for two characters to fit the null-terminator.

Also remember that the size provided in array declarations is the actual number of elements, not the top index. So when you define input_string as an array of a single element, that means it only have a single element, with index 0.

If you want to read a string containing two characters you need to define an array of three characters: The two characters in the string plus the null-terminator.

You also need to limit the number of characters that scanf will read, so users can't input arbitrarily long strings and cause buffer overflows.

In short:

// Place for two characters, plus null-terminator
char input_string[3];

// Limit the input to only two characters (not including null-terminator)
scanf("%d %2s", &input_year, input_string);

On another note, if you want to use the date input in any other way than a single number, I recommend you read it as separate year, month and day:

unsigned year, month, day;
char input_string[3];

scanf("%4u%u%2u %2s", &year, &month, &day, input_string);

Also note that I use unsigned as a type (and the corresponding scanf format) as the input can't and shouldn't be negative.

You should also really check what scanf returns, to make sure the input is valid.

And lastly, to better handle input validation, I recommend you use fgets to read the input into a large string. Then use e.g. sscanf (with checking return values) to attempt to parse the input.

CodePudding user response:

Your input buffer is too small

char input_string[1];

That reserves space for one character. You need 3 in your case of 'rd'. The extra one is because c always adds a 0 at the end of a string. So you need

char input_string[3];

at least if you are sure its always 2 characters

Or maybe

char input_string[10];

if it could be larger. You can tell sprintf the max size you will accept like this (say 2 in your case)

scanf("%d %2s", &input_year, input_string);
-----------^
  • Related