[SOLVED] number and string during same input

Issue

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.

Solution

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.

Answered By – Some programmer dude

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *