For an exercise, I can take two integers or two strings. If I want integers as input, I need to convert them to strings or if I take strings as input, I need to convert the strings to integers. When i want to input two strings at once, somehow, they are being concatenated. If I take integers, when I want to convert using snprintf, the strings are being concatenated again!
When I take strings as input:
#include <stdio.h>
int main(){
char n[5],m[5];
scanf("%s %s",n,m);
printf("%s %s\n",n,m);
}
The input is 12345 56789
but the output is 1234556789 12346
the scanner thinks that "12345 56789" is a whole string.
How is this happening? Didn't I specify that n can only hold 5 char? If I reduce n[5] to n[1] the output is 156789 56789
When I take integers as input and try to convert using snprintf
:
#include <stdio.h>
#include <stdlib.h>
int main(){
int g,w,cnt=0;
scanf("%d %d",&g,&w);
char n[5], m[5];
snprintf(n,6,"%d",g);
snprintf(m,6,"%d",w);
printf("%s\n",n);
printf("%s\n",m);
}
If I input 12345 67894 Output is 1234567894 67894.
Same problem as before. What can I do to fix this issue?
When defining a char
array for storing a string in C, you have to take in account the end of string character (\0
) that scanf
put into the array implicitly.
So, if you define a char[5]
you will be able to store string composed by 4 characters because the last position of array is used for \0
.
Change your code in this way:
#include <stdio.h>
int main(){
char n[6], m[6];
scanf("%s %s", n, m);
printf("%s %s\n", n, m);
}
A little improvement of your code, with a check of the return value from scanf
, is the following:
#include <stdio.h>
int main(void){
char n[6], m[6];
int retCode = scanf("%5s %5s", n, m); // format with max number of chars per array
if(retCode == 2) { // 2 means that both n and m was successfully populated
printf("%s %s\n", n, m);
} else {
printf("Error occurred. Maybe strings exceeded the array spaces\n");
}
}
This way you can check if user inserted only one string or if there was some problem during the extraction from stdin
into the char
arrays.