Thread: scan f seems to crash my program

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    9

    scan f seems to crash my program

    hi guys. sorry if this is a newbie question but i cant get my code to work! it compiles and runs but when i get to the point of inputing a character, the program crashes/wont accept any input. this is a piece of homework i have and it is to write a hangman game. the comments are from my lecturer because we were handed a skeleton code to work from. any help would be appreciated because it is due in 4 hours!

    my code is

    Code:
    #include<stdio.h>
    #include<string.h>
    #include <stdlib.h> 
    #include <time.h> 
    
    char *list[12] ={
          "banana", "programmer",
          "tongue", "favourite",
          "serendipity", "sportman",
          "harmony", "goalkeeper",
          "operation", "hamstring",
          "vibration", "wonderful"
         };
    
    int main(void)
    {
        int  wordi, lives;
        char word[20];
        char str1[20];
        int wordlength;
        int i;
        char x;
        int win;
        char *ptr;
        char yesno;
    
        srand((unsigned int)time(NULL));
    
        while (1){
        // this block select a random word to start a game 
        wordi =  rand() % 12; 
    wordi=1;
        printf("\n rand index is %d \n ", wordi);        
        strcpy(word,list[wordi]);
        
        // set variables to initial state
        lives=8;
        
        strcpy(str1,word);
        wordlength=strlen(str1);
    
    if (wordi=1){
    strcpy(str1,"______");}
    else if (word=="programmer"){
    strcpy(str1,"__________");}
    else if (word=="tongue"){
    strcpy(str1,"______");}
    else if (word=="favourite"){
    strcpy(str1,"_________");}
    else if (word=="serendipity"){
    strcpy(str1,"___________");}
    else if (word=="sportman"){
    strcpy(str1,"________");}
    else if (word=="harmony"){
    strcpy(str1,"_______");}
    else if (word=="goalkeeper"){
    strcpy(str1,"__________");}
    else if (word=="operation"){
    strcpy(str1,"_________");}
    else if (word=="hamstring"){
    strcpy(str1,"_________");}
    else if (word=="vibration"){
    strcpy(str1,"_________");}
    else if (word=="wonderful"){
    strcpy(str1,"_________");}
    
       printf("%s",str1);
    
        printf("\n Let's start. You have %d lives  \n ", lives);
    
        while(1)
        {
           while (lives != 0){
           printf("\n  Next x: ");
           scanf("%c",&x);
           printf("%c",x);
    	
    	for (i=0;i=wordlength;i++){
    	if (word[i]==x){
    	str1[i]==word[i];
    	}
    	else {}
    	}
    
    	ptr=strchr(str1, '_');
    	if (ptr==NULL){win=1;}
            else{}
    
    
           // update stare accordingly and print one of the follwing messages
    	if (win == 1){
            printf(" The word is %s, you have won !! \n",str1);}
            else if (lives != 0){
            printf(" Lives: %d,  Current word: %s \n", lives, str1);}
    	else if (lives ==0){
            printf("  Game Over  \n");}
    	
    
        
        
    
    }
    
        // this loops ask the player if he wants to play again and waits for x Y/N
        // you don't need to change this 
        while (1);
        {
          printf("\n Do you want to play again [Y/N] \n");
          scanf("%s",&yesno);
          if ((yesno == 'N') || (yesno == 'n'))  
            return 0;
          if ((yesno == 'Y') ||  (yesno == 'y'))  
            break;
       }
       
       // goes to play again 
      } 
    }
    }

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by jakeonator View Post
    hi guys. sorry if this is a newbie question but i cant get my code to work! it compiles and runs but when i get to the point of inputing a character, the program crashes/wont accept any input. this is a piece of homework i have and it is to write a hangman game. the comments are from my lecturer because we were handed a skeleton code to work from. any help would be appreciated because it is due in 4 hours!
    A few things wrong here...

    Code:
    if (wordi=1){
    strcpy(str1,"______");}
    else if (word=="programmer"){
    strcpy(str1,"__________");}
    else if (word=="tongue"){
    strcpy(str1,"______");}
    else if (word=="favourite"){
    strcpy(str1,"_________");}
    else if (word=="serendipity"){
    strcpy(str1,"___________");}
    else if (word=="sportman"){
    strcpy(str1,"________");}
    else if (word=="harmony"){
    strcpy(str1,"_______");}
    else if (word=="goalkeeper"){
    strcpy(str1,"__________");}
    else if (word=="operation"){
    strcpy(str1,"_________");}
    else if (word=="hamstring"){
    strcpy(str1,"_________");}
    else if (word=="vibration"){
    strcpy(str1,"_________");}
    else if (word=="wonderful"){
    strcpy(str1,"_________");}
    1) C does not know how to compare strings across the == operator. You need to use strcmp() instead.

    2) if you're simply looking for the right number of underscores, just use the memset() and strlen() functions.

    Code:
    for (i=0;i=wordlength;i++){
    if (word[i]==x){
    str1[i]==word[i];	}
    	else {}
    	}
    
    	ptr=strchr(str1, '_');
    	if (ptr==NULL){win=1;}
            else{}
    1) The else statements are not needed here, they can be removed with no effect on the program.

    2) See the part I bold faced... Are you assigning or comparing?

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    9
    i know it's written very poorly. thanks for the whole memset thing for the underscores!!! for the 2nd part, it is supposed to assign word[i], which would be the letter from the word to the same position in str1, i.e. so if the original word was hamstring, str1 becomes ________, and is the player guesses a, it loops through the original word and if the letter matches, changes the relevant underscore in str1 to that letter, i.e. printing _a_______ also, i forgot to add that the program is set to only work for wordi=1, which should be programmer, but i stupidly used the underscores for banana

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    9
    oh and x is the guessed letter

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    In that bold faced statement you need to use a single equals sign. Single assign ... double compare

    So after cleaning up the extraneous else statements you end up with...
    Code:
    for (i = 0; i < wordlength; i++)
      if (word[i] == x)
        str1[i] = x; 
    
    ptr = strchr(str1, '_');
    if (ptr == NULL)
      win = 1;
    Notice how a few spaces makes the code more readable... The compiler doesn't care, but we humans usually do.

    I rather like the use of strchr() to determine the win, very clever. You could simplify it like this...
    Code:
    if (strchr(str1, '_') == NULL)
      win = 1;
    Last edited by CommonTater; 06-12-2011 at 06:01 AM.

  6. #6
    Registered User
    Join Date
    Jun 2011
    Posts
    9
    allright, but when i run my program, it still doesnt work. it compiles, and runs, but when i get to the point of inputing a letter, i input and it does nothing, it doesnt even get to the point of printing the character i just input which is the next line. did i write my scanf right? my code now looks like this

    Code:
    #include<stdio.h>
    #include<string.h>
    #include <stdlib.h> 
    #include <time.h> 
    
    char *list[12] ={
          "banana", "programmer",
          "tongue", "favourite",
          "serendipity", "sportman",
          "harmony", "goalkeeper",
          "operation", "hamstring",
          "vibration", "wonderful"
         };
    
    int main(void)
    {
        int  wordi, lives;
        char word[20];
        char str1[20];
        int wordlength;
        int i;
        char x;
        int win;
        char *ptr;
        char yesno;
    
        srand((unsigned int)time(NULL));
    
        while (1){
        // this block select a random word to start a game 
        wordi =  rand() % 12; 
    wordi=1;
        printf("\n rand index is %d \n ", wordi);        
        strcpy(word,list[wordi]);
        
        // set variables to initial state
        lives=8;
        
        strcpy(str1,word);
        wordlength=strlen(str1);
    
    memset (str1,'_',wordlength);
    
       printf("%s",str1);
    
        printf("\n Let's start. You have %d lives  \n ", lives);
    
        while(1)
        {
           while (lives != 0){
           printf("\n  Next x: ");
           scanf("%c",&x);
           printf("%c",x);
    	
    	for (i=0;i=wordlength;i++){
    	if (word[i]==x){
    	str1[i]=word[i];}}
    
    	ptr=strchr(str1, '_');
    	if (ptr==NULL){win=1;}
            else{}
    
    
           // update stare accordingly and print one of the follwing messages
    	if (win == 1){
            printf(" The word is %s, you have won !! \n",str1);}
            else if (lives != 0){
            printf(" Lives: %d,  Current word: %s \n", lives, str1);}
    	else if (lives ==0){
            printf("  Game Over  \n");}
    	
    
        
        
    
    }
    
        // this loops ask the player if he wants to play again and waits for x Y/N
        // you don't need to change this 
        while (1);
        {
          printf("\n Do you want to play again [Y/N] \n");
          scanf("%s",&yesno);
          if ((yesno == 'N') || (yesno == 'n'))  
            return 0;
          if ((yesno == 'Y') ||  (yesno == 'y'))  
            break;
       }
       
       // goes to play again 
      } 
    }
    }

  7. #7
    Registered User
    Join Date
    Jun 2011
    Posts
    9
    or even better could i use 'gets' or something to scan in the letter? if so, how?

  8. #8
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    scanf("%c" ...) can throw you through a loop, since all white space is a match for %c which is different from other formats. The solution is to write " %c" that is, include whitespace in the format so scanf will skip it and read the interesting stuff.

  9. #9
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Ok, running this through Pelles C, I get to enter my first letter, it prints the letter and then just sits there...

    Take a close look at your loop structure for taking guesses... where is the closing brace?... and why is all that code in that loop?
    All you really need at that point is enough code to take the guess and update the word display... Winning or running out of turns should exit that loop and move down to the win/lose test below it. In fact these conditions should probably be part of the while() statement itself... It's not hard to do and gives better control over the loop.

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Also take a look at the structure of this loop...
    Code:
    for (i=0;i=wordlength;i++){
    if (word[i]==x){
    str1[i]=word[i];}}
    The second phrase in a for() statement is not an exit condition, it is a condition of continuation (like in while() loops)...

    Try it like this...
    Code:
    for (i = 0;i < wordlength; i++)
      if (word[i]==x)
        str1[i]=word[i];

  11. #11
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Code:
    while (1);
    That's an infinite loop because of the ;

  12. #12
    Registered User
    Join Date
    Jun 2011
    Posts
    9
    ok, so what exactly do you mean about the loops and parenthesis? i changes a little code and now it wont complie

    Code:
    #include<stdio.h>
    #include<string.h>
    #include <stdlib.h> 
    #include <time.h> 
    
    char *list[12] ={
          "banana", "programmer",
          "tongue", "favourite",
          "serendipity", "sportman",
          "harmony", "goalkeeper",
          "operation", "hamstring",
          "vibration", "wonderful"
         };
    
    int main(void)
    {
        int  wordi, lives;
        char word[20];
        char str1[20];
        int wordlength;
        int i;
        char x;
        int win;
        char *ptr;
        char yesno;
    
        srand((unsigned int)time(NULL));
    
        while (1){
        // this block select a random word to start a game 
        wordi =  rand() % 12; 
    wordi=1;
        printf("\n rand index is %d \n ", wordi);        
        strcpy(word,list[wordi]);
        
        // set variables to initial state
        lives=8;
        
        strcpy(str1,word);
        wordlength=strlen(str1);
    
    memset (str1,'_',wordlength);
    
       printf("%s",str1);
    
        printf("\n Let's start. You have %d lives  \n ", lives);
    
        while(1)
        {
           while (lives != 0){
           printf("\n  Next x: ");
           scanf("%s",&x);
           printf("%s",x);
    	
    	for (i=0;i<wordlength;i++){
    	if (word[i]==x){
    	str1[i]=word[i];}}
    
    	if (strchr(str1, '_') == NULL)
              win = 1;
    
    
           // update stare accordingly and print one of the follwing messages
    	if (win == 1){
            printf(" The word is %s, you have won !! \n",str1);}
            else if (lives != 0){
            printf(" Lives: %d,  Current word: %s \n", lives, str1);}
    	else if (lives ==0){
            printf("  Game Over  \n");}    
    
    }
    
        // this loops ask the player if he wants to play again and waits for x Y/N
        // you don't need to change this 
        while (1);
        {
          printf("\n Do you want to play again [Y/N] \n");
          scanf("%s",&yesno);
          if ((yesno == 'N') || (yesno == 'n'))  
            return 0;
          if ((yesno == 'Y') ||  (yesno == 'y'))  
            break;
       }
       
       // goes to play again 
      } 
    }
    }
    it no longer wants to compile and all i get is a segmentation fault. what the hell is that?
    also could you tell me where i screwed up, cause i cant find it.

    also, the mass of code in the loop is because the program needs to repeat until the player inputs a 'no' for 'play again', and i also need to implement a break for the program so that is the player inputs break the program terminates.

    also, sorry about the spaces and such, i guess im lucky that all the programs are marked by a computer, and not the teacher

  13. #13
    Registered User
    Join Date
    Jun 2011
    Posts
    9
    also, i use also a lot

    also

    also, i am really new to c...

    also......

  14. #14
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by jakeonator View Post
    when i get to the point of inputing a letter, i input and it does nothing, it doesnt even get to the point of printing the character i just input
    You will have to input the letter and hit enter, because stdin is buffered that way. Stdout is also buffered that way, which adds an additional complication that might be hard to see the significance of. Try this (nb, the .h for sleep() is platform specific, "unistd.h" works on linux).

    Code:
    #include <stdio.h>
    #include <unistd.h> // platform specific
    
    int main() {
    	char ch;
    
    	while (1) {
    		scanf("%c", &ch);
    		printf("%c", ch);
    		sleep(1);
    		printf("->");
    		//fflush(stdout);
    	}
    
    	return 0;
    }
    If I enter "asdf" (four characters) and hit enter, I will wait four seconds and then see, all at once:

    a->s->d->f->

    This is because the stdin buffer does not get passed on to the program until you enter a newline ('\n'). Then, the stdout buffer does not get displayed until it reaches a \n. So it reads in one character at a time, outputs that character, then sleeps for one second and outputs "->". But you will not see the output until the output is flushed because of a \n.

    However, you can force stdout to flush with:

    fflush(stdout);

    So if you uncomment that line at the end of the loop, recompile, and do the same thing again,
    you will see:

    a->s->d->f->

    Appear one character (plus "->") every second until the end.

    Unfortunately you cannot force stdin the same way, so you do have to press enter and you have to take into account that '\n' count as a character.

    These are the realities of the system you have to work within.

    BTW, this:

    Code:
        while (1);
        {
          printf("\n Do you want to play again [Y/N] \n");
          scanf("%s",&yesno);
    Is bad -- in fact your compiler should warn you about the type mismatch. You are reading a string into a single char. %s will not include the newline (it gets left in the stdin buffer), but scanf will I include a '\0' (null terminator) with a string, so even if the user politely enters only one character, you will still be writing a minimum of 2 bytes into a (one byte) char. This is a potential seg fault.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  15. #15
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    LOL.. me also...

    You need to check your loop structures... make a list of which loops you need, how they're governed and what they need to do for you...

    For example:
    You need one overall loop that repeats until the user chooses to exit... how does that work?
    You need one loop to take the turns of the game... what needs to be in it?
    etc.

    From that re-organize your code so that each loop encapsulates *only* the necessary code, and you have no loops that you don't need.

    FWIW... I fixed your code here, mostly by removing stuff that wasn't necessary...
    There are still a couple of minor issues we can deal with once you have these loops sorted...
    Last edited by CommonTater; 06-12-2011 at 06:56 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why does this program crash when I do this?
    By Witch in forum C Programming
    Replies: 4
    Last Post: 03-18-2010, 07:10 PM
  2. program crash
    By l2u in forum C++ Programming
    Replies: 11
    Last Post: 09-07-2006, 12:58 PM
  3. Why Does My Program Crash?
    By Grantyt3 in forum C++ Programming
    Replies: 20
    Last Post: 09-29-2005, 05:34 PM
  4. Why does the program crash?
    By SkyRaign in forum C++ Programming
    Replies: 8
    Last Post: 09-25-2005, 10:06 AM
  5. Program crash ?!
    By tilex in forum C++ Programming
    Replies: 6
    Last Post: 12-21-2004, 08:47 PM

Tags for this Thread