Jump to content

Issues with a while loop

- - - - -

  • Please log in to reply
2 replies to this topic

#1
TallMike

TallMike

    Newbie

  • Members
  • Pip
  • 2 posts
hello everyone. I'm having a problem with a program I'm writing that is supposed to take a first and last name and write them to file. I'm trying to put it all in a while loop so that the user can either add more names or stop the writing to the file but when I choose to write more names it just adds the original name typed in. It's like instead of actually asking me for a new name and scanning it, it just asks and then scans what was typed in the first time. I'm not sure whats wrong.

Here's my code:
#include <stdio.h>
#include <string.h>

int main(void)
{
     
    int more = 1;
    char first[15], last[20];
    FILE *file;
    
    file = fopen("user_name_list.txt", "a+");
     
    if(file == NULL) 
    {
        printf("Error: can't open file.\n");
        return 1;
    }
    
    fprintf(file, "Last     First\n"
                  "--------------\n");
    
    while (more == 1)
    {
        char line[20]; 
        
        printf("\nEnter your first and last name separatted by a space> ");
        
        fgets(line, sizeof(line), stdin);
        
        sscanf(line, "\n%s %s", first, last);
        
        printf("\n%s, %s", last, first);
        
        fprintf(file, "\n%s, %s", last, first);
        
        printf("\nAre there more names to be added? (enter '1' for yes or '2' for no)> ");
        
        scanf("%d", &more);
        
    }
    
    

    return 0;        
}
thank you all for the help

Mike

Edited by WingedPanther, 31 March 2010 - 11:43 AM.
add code tags (the # button)


#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
Why not print line to the screen to see what's happening?
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
TallMike

TallMike

    Newbie

  • Members
  • Pip
  • 2 posts
When I print line it prints the original name I entered. It's like it enters the original name for me after it asks for the next name.

And when I put all of the arrays inside the while loop it enters blanks for the first and last names. So I know that if they are declared inside they're definitely being re-declared every time it enters the while loop, but it still enters the blank value after the new name is asked for.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users