scan f seems to crash my program

This is a discussion on scan f seems to crash my program within the C Programming forums, part of the General Programming Boards category; The reason you do not see the character right away has nothing to do with the logic of your loops ...

  1. #16
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    The reason you do not see the character right away has nothing to do with the logic of your loops (good or bad). It is because you did not flush stdout, and without being flushed, the stdout contents are buffered until a newline is found. Your newline was left in stdin because you only read a single character from it.
    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

  2. #17
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by MK27 View Post
    The reason you do not see the character right away has nothing to do with the logic of your loops (good or bad). It is because you did not flush stdout, and without being flushed, the stdout contents are buffered until a newline is found. Your newline was left in stdin because you only read a single character from it.
    How odd that I have it working perfectly here without a single toilet handle in sight...

  3. #18
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by CommonTater View Post
    How odd that I have it working perfectly here without a single toilet handle in sight...
    LOL well if you rearrange the loop fortuitously enough...then you use it exactly right because you wrote it...you could end up with a functional but very delicate program which is a product of working around an issue you did not understand/account for. Very likely, it will have some slightly odd behavior, or break easily when you change the code.

    That's not a worthwhile goal. Accounting for everything that flows through stdin and stdout, including the newlines, is fundamental. You do not actually have to use fflush, there are other choices (such as inserting a newline):

    Code:
    printf("%c\n", ch);
    The only way to understand those choices is to understand the nature of stdin and stdout. That may take a bit of experimentation. Leaving the stdin newlines around and rearranging the logic so that they seem harmless is not a good choice. The OP needs to get some basic things straight in his/her head before playing around with complications.
    Last edited by MK27; 06-12-2011 at 07:39 AM.
    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

  4. #19
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by MK27 View Post
    The only way to understand those choices is to understand the nature of stdin and stdout. That may take a bit of experimentation. Leaving the stdin newlines around and rearranging the logic so that they seem harmless is not a good choice. The OP needs to get some basic things straight in his/her head before playing around with complications.
    Newlines happen more or less by course in the formatting of output into reasonable lines of display, so it's not a major issue in most cases. Yes, I do agree the OP needs to learn about streams and such, but perhaps not at the risk of complicating a simple homework exercise that has other problems to be looked at first...

  5. #20
    Registered User
    Join Date
    Jun 2011
    Posts
    9
    ok. so after much grooming my code looks like this:

    Code:
    #include<stdio.h>
    #include<string.h>
    #include <stdlib.h> 
    #include <time.h> 
    
    char *list[12] ={			//variables and stuff
          "banana", "programmer",
          "tongue", "favourite",
          "serendipity", "sportman",
          "harmony", "goalkeeper",
          "operation", "hamstring",
          "vibration", "wonderful"
         };
    
    int main(void)				// start of main function
    {
        int  wordi, lives;			//more variables
        char word[20];
        char str1[20];
        int wordlength;
        int i;
        char guess;
        int win;
        char *ptr;
        char yesno;
    
        srand((unsigned int)time(NULL)); //  <----------- does anyone know what this line does???
    
    
    
    
    //working code body
    
    
        
    while(lives!=7000)     //start of game while (7000 is so it doesnt end unless return 0)
    {
    
    
    wordi =  rand() % 12; 				// word selection  (this particular line will be 
    printf("\n rand index is %d \n ", wordi);       // replaced by the computer so it can control the
    strcpy(word,list[wordi]);			// word in order to test and mark the code
    
    
    
    lives=8;				// initial settings
    
    strcpy(str1,word);
    
    wordlength=strlen(str1);
    
    memset (str1,'_',wordlength);
    
    printf("\n Let's start. You have %d lives  \n ", lives);
    
    printf("%s",str1);
    
    while (lives>0) // start of guesses while
    	{
    	printf("\n  Next Guess: ");
    	scanf("%c",&guess);
    	printf("%c",guess);
    	
    	for ( i=0 ; i<wordlength ; i++ ){
    		if ( word[i] == guess){
    		str1[i] = word[i];}
    		else{
    		lives=lives-1;}}
    
    	if (strchr(str1, '_') == NULL){
    	win = 1;}
    	else{}
    
    	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");} 
    
    	} // end of guesses while
    
    printf("\n Do you want to play again [Y/N] \n");
    scanf('%c',&yesno);
    if (yesno == 'N')
    return 0;
    else if (yesno == 'n')
    return 0;
    else if (yesno == 'Y')  
    break;
    else if (yesno == 'y')
    break;
    else
    return 0;
    
    
    } // end of game while
    
    return 0;
    
    } // end of main function
    i'm still working on the yes/no rester the game thingo because it has the whole multi charachter constant thing going, but otherwise, it compiles and kinda works, gotta skrew aroung with the lives and stuff.

    mr commontater, if i could beg of you please, could you post your working copy of the code so i can compare it to mine and see why mine doesnt work!!! i only have half an hour until submission is due, but i plan to keep working on my copy after that till it works properly, you know, the whole learning thing

  6. #21
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by jakeonator View Post
    i'm still working on the yes/no rester the game thingo because
    That is where the '\n' left in stdin will come out, to unfortunate effect:

    Code:
    while (lives>0) // start of guesses while
    	{
    	printf("\n  Next Guess: ");
    	scanf("%c",&guess);
    Notice you read one character, but the user had to enter (at least) TWO -- the letter plus a newline. That newline is still in the stdin buffer, so at your next read:

    Code:
            printf("\n Do you want to play again [Y/N] \n");
            scanf('%c',&yesno);
    "yesno" now contains that '\n', and there are (probably) two more characters left in stdin: whaterver y or n plus another '\n'. Everything will start to foul up at that point, because the number of characters left in the stdin buffer will increase at each iteration. And if the user actually enters "yes" instead of just 'y' the problem will get worse.

    Using scanf("%c") alone is simply too delicate -- it depends on the user doing the right thing, and inevitably leaves a newline behind. So, altho it seems tedious, you need something more robust to deal with input. Consider this:

    Code:
    #include <stdio.h>
    
    int main() {
    	char ch, discard;
    
    	while (1) {
    		scanf("%c", &ch);
    		discard = 0;
    		while (discard != '\n') scanf("%c", &discard);
    		printf("%c<-\n", ch);
    	}
    
    	return 0;
    }
    This reads the first character entered and then removes everything else from the stdin buffer. What happens?

    asdf
    a<-
    dfgh
    d<-
    yes
    y<-
    no
    n<-


    Now you have a foolproof way of getting input and tidying up afterward, to avoid issues at your next read.

    Quote Originally Posted by CommonTater View Post
    Newlines happen more or less by course in the formatting of output into reasonable lines of display, so it's not a major issue in most cases.
    Malarky. That is a "horseshoes and handgrenades" approach. You have to consciously, in code, account for 100% of the data going in and out, not just trust your luck and hope for the best. Even if this seems like nit picking, it is the difference between clear, robust code, and unclear, fragile code. You start with clear, robust fragments and build up a clear, robust whole. Rearranging lazy, problem prone fragments cannot lead anywhere but a lazy, problem prone whole that "seems to work now, and I didn't even have to worry about the little details". Bad habit! If the OP is in school, that could be the difference between an A and C, and in "real life", I just have to pray you didn't work on the electronics in my car

    In fact, even the while(discard) loop has a flaw: if the user just hits enter, that's what ch will be, then we will hang, because that while does not have anything to read. Really "getchar" should be a reusable function:

    Code:
    char getchar() {
    	char ch, discard;
    	scanf("%c", &ch);
    	if (ch == '\n') return ch;
    	while (discard != '\n') scanf("%c", &discard);
    	return ch;
    }
    Of course, there is a standard function like this (getchar or getch), hint hint. However, it may not work exactly this way, be sure to test your premises (aka, assumptions) when using new tools.
    Last edited by MK27; 06-12-2011 at 09:14 AM.
    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

  7. #22
    Registered User
    Join Date
    Jun 2011
    Posts
    9
    well either way, thats the assignment deadline gone and passed, with my glorious script scoring a 0 out of 0... oh well... i think i can submit later, but for less marks and whatnot. either way, you guys were very helpful. where i am it is midnight now, and the last busses start their run, so i'll be heading home. ill be back on in about an hour, trying to continue fixing this code, or trying to figure out how to install a compiler at my house. do any of you guys know a good compiler that works on windows? or is this some sort of punchline for all programming jokes, and i should just install some version of linux/unix. so then what unix/linux variant should i use???

  8. #23
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by jakeonator View Post
    do any of you guys know a good compiler that works on windows? or is this some sort of punchline for all programming jokes, and i should just install some version of linux/unix. so then what unix/linux variant should i use???
    If you are working on unix at school then minGW (for windows) might be good as it uses gcc, the GNU compiler, which (at least originally) was a clone of cc, the unix compiler, and may very well be exactly what you are using anyway.

    MinGW | Minimalist GNU for Windows
    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

  9. #24
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by jakeonator View Post
    well either way, thats the assignment deadline gone and passed, with my glorious script scoring a 0 out of 0... oh well... i think i can submit later, but for less marks and whatnot. either way, you guys were very helpful. where i am it is midnight now, and the last busses start their run, so i'll be heading home. ill be back on in about an hour, trying to continue fixing this code, or trying to figure out how to install a compiler at my house. do any of you guys know a good compiler that works on windows? or is this some sort of punchline for all programming jokes, and i should just install some version of linux/unix. so then what unix/linux variant should i use???
    Ok, since your submission deadline has passed, I'll post my version for you... (So now it's *not* homework, there's a forum policy about that)...

    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 str1[20];
        int wordlength;
        int i;
        char x;
        int win;
        char yesno;
    
        srand(time(NULL));
    
        do 
          { // this block select a random word to start a game 
            wordi =  rand() % 12; 
            // set variables to initial state
            wordlength = strlen(list[wordi]);
            lives = wordlength * 2;
            win = 0;
            memset(str1,0,20);
            memset (str1,'_',wordlength);
            printf("\n Let's start. You have %d lives  \n ", lives);
    
            // game loop
            while (lives != 0)
              { printf("\nWord :\t%s\n\n%d Tries left, Next : ", str1, lives);
                scanf(" %c",&x);
                lives--;
                for (i = 0; i < wordlength; i++)
                  if (list[wordi][i] == x)
        	         str1[i] = x;
                // check for win
                if(!  strchr(str1, '_'))
                  { win=1;
                    break; } }
    
            // update state accordingly and print one of the follwing messages
            if (win == 1)
              printf("The word is %s, you have won !!\n",str1);
        	  else 
              printf("Game Over, better luck next time.\n");   
    
           // ask the player if he wants to play again
           printf("\n Do you want to play again [Y/N] :");
           scanf(" %c",&yesno);   }  // test for end of game
       while((yesno == 'Y') || (yesno == 'y'));  
      
     return 0; }
    If you're looking for a good c-99 compliant compiler to use on Windows... have a look at Pelles C
    Last edited by CommonTater; 06-12-2011 at 09:18 AM.

  10. #25
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,641
    Well, you're certainly a trusting soul Common Tater.

    srand((unsigned int)time(NULL)); // <----------- does anyone know what this line does???
    Let me google that for you

  11. #26
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by rags_to_riches View Post
    Well, you're certainly a trusting soul Common Tater.
    After what I've been through this last week (Did ya miss me?) I gotta start someplace...

Page 2 of 2 FirstFirst 12
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, 07:47 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21