Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do strings get printed twice when using printf in C?

Tags:

c

printf

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?

like image 232
Cesare Avatar asked May 14 '15 16:05

Cesare


People also ask

Why is my C code printing twice?

"prints out "Input a character" twice each time" is because user typed 2 keys.

What is the problem with printf in C?

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.

What should we do if we want to print a string in C?

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);

Why does C use printf and not print?

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.


1 Answers

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.

like image 198
timrau Avatar answered Sep 28 '22 16:09

timrau