Issue with fprintf

0 dan mendez · May 25, 2015
#include <stdio.h>
#include <stdlib.h>

calcBonus(int years);

int main()
    FILE * fP;
    fP = fopen("bonus.txt", "w+");
    char name[25];
    int yearsWorked;
    int howMany, i;

    printf("How Many employees are you calculating the bonus for: ");
    scanf("%d", &howMany);

    for(i=0; i<howMany; i++) {
        printf("\n\nEnter the name of the employee: ");
        scanf("%s", &name);
        printf("\nEnter the years worked: ");
        scanf("%d", &yearsWorked);
        fprintf(fP, "%s \t\t", name);
        fprintf(fP, "%d\n", calcBonus(yearsWorked));



    return 0;

int calcBonus(int years) {

    int bonus = years * 250;

    if (years>10){
        bonus += 1000;

    return bonus;


My problem is this: When it prints to a file, it is including the first letter of the previous name. Wtf? Also, I can't get it to print with fputs(), I have to use fprintf().

Post a Reply


Oldest  Newest  Rating
0 dan mendez · May 25, 2015
You sir, are a genius! That worked perfectly.

I see what you are saying, kinda... 

The array is looking kinda like this

Name One: John
name = John
Name Two: Sam
name = JSam
Name Three: Pam
name = JSPam

I was basically telling scan to begin writing by adding name

**Note: I am on day two of learning C, so I appreciate all the help!

The other thing you mention went completely over my head, I thought the function was returning "bonus" ? I'm about to google Function Return Type!
0 dan mendez · May 25, 2015
nvm! I see what you mean... i forgot the return type in the prototype. I'm surprised it didnt give me a warning!
0 c student · May 25, 2015
dodgy function declaration here:
calcBonus(int years);   /* Missing return type */

you've declared a name array of 25 characters and when you are scanning into the array, you are effectively overwriting the characters in the array, however, when you increment with each loop, you are leaving the first character in the array untouched.
Here's an example:
First scan:
i = 0
name input: Guy One
name[0] = S
name = Guy One
Second scan:
i = 1
name input: Guy Two
name[1] = G
name = SGuy Two
Since your name[0] remains as S
You should scan into "name" instead of "&name[index]"

@ Arjun Patel
From man page of scanf():
String input conversions store a terminating null byte ('\0') to mark the end of the input; the maximum field width does not include this terminator.
0 Dol Lod · May 25, 2015
When you use %s, whatever string you are putting must end with the null byte or it could result in unexpected behavior. Try nulling name out first and then using it. 
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator