My program asks the user to provide a string, which will be copied into an array of characters. Then, with a for
loop, the program simply copies the elements of the first array into the second array.
int main() {
int i;
char string1[4], string2[4];
// Get the first string
printf("Insert your string: ");
scanf("%s", string1);
// Copy the values into the second array
for (i = 0; i < 4; i++) {
string2[i] = string1[i];
}
// Print the second string
printf("%s", string2);
return 0;
}
However, when I print the string using the printf()
function the string gets printed twice.
Let's say I input the word
bars
The output will be
barsbars
Why is this happening?
"prints out "Input a character" twice each time" is because user typed 2 keys.
The printf functions are implemented using a variable-length argument list. Arguments specified after the format string are passed using their inherent data type. This can cause problems when the format specification expects a data object of a different type than was passed.
If we want to do a string output in C stored in memory and we want to output it as it is, then we can use the printf() function. This function, like scanf() uses the access specifier %s to output strings. The complete syntax for this method is: printf("%s", char *s);
By the way, printf is not part of the C language; there is no input or output defined in C itself. There is nothing magic about printf ; it's just a useful function that is part of the standard library of routines that are normally accessible to C programs.
char string1[4], string2[4];
4-element char array is not enough for 4-character strings. You need one more for the terminating '\0'
character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With