#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Location
    Karachi, Pakistan
    Posts
    16
    Rep Power
    0

    Y or N prompt code in C


    I'm a Beginner trying to learn C and I'd just now come across an exercise in the ebook I'm learning out of that says to write a program that asks a Yes/No prompt and I'm stuck as to how I should do it.

    What I have so far is this:

    #include <stdio.h>

    int main()
    {
    char answer;
    int Y,N,y,n;
    printf("Are you man?");
    getchar();

    if(answer == Y || answer == y)
    {
    printf("Hello, Mr. User!");
    }
    if(answer == N || answer == n);
    {
    printf("Hellow, Mrs. User!");
    }
    }
    I want it to where it just shows "Hello, Mr. User!" if I press "Y," but as it is now it's showing both messages at once (it's also showing the one that should only show if "N" is pressed). What am I doing wrong?

    It'd be appreciated if I could some help with this. Thanks a lot.
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,220
    Rep Power
    2222
    1. You declared main to return an int and were very correct to do so. But you didn't return an int. At the end of main, you at least need a return 0; statement.

    2. Use code tags. Code tags preserve your code's indentation, whereas quote tags do not. Of course, you also need to indent your code properly and consistently.

    3. If you want to test what the user has input, then you need to read input from the user. You did not do that. You apparently want to use the variable, answer, to store the character that the user inputs. So do that! As your program is now, you just throw away that input character. Save it in answer!

    4. What are the variables, Y, y, N, and n and what are you using them for? Stupid question: do you intend Y to be a char that contains 'Y', y to be a char that contains 'y', N to be a char that contains 'N', and n to be a char that contains 'n'? If so, then why didn't you do that? Or for that matter, you could have just compared answer to the literal values 'Y', 'y', 'N', and 'n'.

    5. Another problem with those four variables is that you compare them to answer, but you never ever assign any values to any of them. That's called an uninitialized variable error, which is a very serious error, especially when you start working with pointers. Never ever use a variable which has not been ininitilized to a known value. Since they are all local variables, they all contain random garbage. If you use random garbage, you have no idea what the results will be.

    6. You say "but as it is now it's showing both messages at once". I have trouble believing that, since the possibility of answer containing the exact same random garbage as either Y or y should be very small. Especially since the higher-order three bytes of Y or y would have to all be zero for that to happen.

    7. Of course it will always print out "Hellow, Mrs. User!". That is because that printf is not in the least bit controlled by the preceding if-statement, since you told that if-statement to do nothing whatsoever if true. Look at that code:
    Code:
        if(answer == N || answer == n);
        {
            printf("Hellow, Mrs. User!");
        }
    Now do you see that extraneous semicolon at the if-statement? That is what tells the if to do nothing if true.
    Last edited by dwise1_aol; December 19th, 2013 at 03:37 PM.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Location
    Karachi, Pakistan
    Posts
    16
    Rep Power
    0
    Okay, thanks for the reply.

    Well, putting that semicolon at the end of the second if and not having it return an int at the end were both stupid mistakes on my part. Thanks for pointing them out.

    I tried to fix the code, but I'm getting this error message now:
    C:\Users\Osman\Documents\BegC4D\ex0816\main.c|7|error: expected identifier or '(' before '=' token|
    This is the code:
    #include <stdio.h>

    int main()
    {
    char answer;
    int Y,N;
    char = (Y || N);
    printf("Are you a man?");
    getchar();

    if(answer == Y)
    {
    getchar();
    printf("Hello, Mr. User!");
    }
    if(answer == N)
    {
    getchar();
    printf("Hello, Mrs. User!");
    }
    return(0);
    }
    If there are still any stupid mistakes in there, please point them out. And I'll apologize for any waste of time I may be causing for you in this.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,931
    Rep Power
    481
    Code:
    #include <stdio.h>
    
    int main()
    {
      char answer, upper_case_answer;
      fputs("Are you a man?  ",stdout); /* lambert, #1.  Use printf only when conversions are required. */
      fflush(stdout);		    /* corrects interaction on lambert's odd configuration */
      answer = getchar();		    /* dwise1 #3 */
    
      upper_case_answer = answer & (~ ' ');	/* lambert, #2 introduce extraneous parenthesis */
    
      if('Y' == upper_case_answer) /* dwise1 #4 *//* lambert, #3 eliminate typo answer = 'Y' */
        {
          getchar();
          puts("Hello, Mr. User!");
        }
      if('N' == upper_case_answer)
        {
          getchar();
          puts("Hello, Mrs. User!");
        }
      return 0;		      /* lambert, #4 extraneous parenthesis */
    }
    Last edited by b49P23TIvg; December 20th, 2013 at 09:17 AM. Reason: lower corrected to upper
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,220
    Rep Power
    2222
    Please to not ignore what we tell you.

    Yet again, USE CODE TAGS! What part of that could you possibly not be able to understand?

    Here is what your code should look like:
    Code:
    #include <stdio.h>
    
    int main()
    {
        char answer;
        int Y,N;
        char = (Y || N);
    
        printf("Are you a man?");
        getchar();
    
        if(answer == Y)
        {
            getchar();
            printf("Hello, Mr. User!");
        }
        if(answer == N)
        {
            getchar();
            printf("Hello, Mrs. User!");
        }
        return(0);
    }
    Make it so.

    Yet again: you need to read input from the user. You still are not doing that. getchar() returns the next character that was input. If you do not use that return value or assign it to a variable, then you just threw it away and it is lost. So yet again, save it in answer! You save a value to a variable with an assignment operation, the one that uses =.

    Yet again: What are the variables, Y, y, N, and n and what are you using them for?
    Yet again: do you intend Y to be a char that contains 'Y', y to be a char that contains 'y', N to be a char that contains 'N', and n to be a char that contains 'n'? If so, then why didn't you do that? Or for that matter, you could have just compared answer to the literal values 'Y', 'y', 'N', and 'n'.

    Yet again: Another problem with those four variables is that you compare them to answer, but you never ever assign any values to any of them. That's called an uninitialized variable error, which is a very serious error, especially when you start working with pointers. Never ever use a variable which has not been ininitilized to a known value. Since they are all local variables, they all contain random garbage. If you use random garbage, you have no idea what the results will be.

    Now you have written:
    char = (Y || N);
    That is absolutely meaningless and violates the rules of C syntax.
    1. char is a datatype. Normally, it would be followed by the char variable that you are declaring, but you declare none.
    2. What the hell is (Y || N) supposed to do? Both variables contain garbage! || will evaluate to true if either Y or N is true, so if either Y's or N's garbage value is not zero, then that expression will evaluate to non-zero. And be absolutely useless!

    Read the input character into answer! Compare answer to 'Y' or 'y' or 'N' or 'n'!
  10. #6
  11. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,116
    Rep Power
    1803
    Originally Posted by DragonOsman2
    I'd just now come across an exercise in the ebook I'm learning out of
    It looks like skipped to the exercise without learning the preceeding material.


    You need to assign the answer to a variable, and test the answer. You have declared variables with names that look like the answers, you expect - you have a fundamental misunderstanding of the nature of variables. Your code lacks any evidence that you are have followed the materials thus far.

    Apart from that, if you mention a book, it is always a good idea to tell use what book you are using.

    Often there is no need to explicitly check for both responses when there are only two options, in this case if the use does not answer "Y" do you really car whether the response was "N" or something else?
    C Code:
     
    int answer = getchar() ;
    if( answer == 'Y' || answer == 'y' )
    {
        // "Yes"
    }
    else
    {
        // Not "yes"
    }
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Location
    Karachi, Pakistan
    Posts
    16
    Rep Power
    0
    I'm reading from Beginning Programming with C for Dummies. This exercise was in Chapter 8. I didn't skip to it, but I guess I need to try to pay more attention to what I'm doing. I followed b49P23TIvg's instructions and now the code works fine. It said in the exercise instructions in the book to look back at Chapter 7 for a hint as to what to do in this exercise. I did that, but I didn't quite get what to really do. And the book hasn't said anything about fflush as far as I can recall yet, either, actually.
  14. #8
  15. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,116
    Rep Power
    1803
    Originally Posted by DragonOsman2
    This exercise was in Chapter 8.
    Wow! Eight chapters to get only that far - that must be a really slow book!

    Originally Posted by DragonOsman2
    I followed b49P23TIvg's instructions and now the code works fine.
    Yes but did you understand it!? It is by far not the simplest and most obvious solution, so as a teaching exemplar I would suggest is not ideal - it's a bit too clever perhaps? Abd the use for fputs() and fflush() is frankly somewhat perverse, and probably deliberate on his part to make you think about what you are doing perhaps? If you just use hos code as is, you are not thinking, much less learning. The answer is perhaps designed to work, but to make it rather obvious perhaps that it is not your own work - lest you attempt to hand it in as an assignment solution.

    Originally Posted by DragonOsman2
    And the book hasn't said anything about fflush as far as I can recall yet, either, actually.
    Well done, some evidence of thinking. If you are using Windows, and you simply use printf(), it is unnecessary. I believe that on Linux and possibly other POSIX environments, stdout is not flushed unless a '\n' is output or an explicit fflush() is issued, YMMV.

    I would disagree with the use of fputs() (or even just puts() which would have been more appropriate and simpler), it is a trivial optimisation that serves no real purpose other than to over complicate things and introduce material not yet encountered in your learning.
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Location
    Karachi, Pakistan
    Posts
    16
    Rep Power
    0
    I think I do understand what I did for that one now; taking fflush() out and changing that fputs() to printf() still works and I do understand everything else that's going in the rest of the code, too.

    Anyway, I have another question now. The exercise I'm doing now is like so; the book gave me this example code and told me try it out:
    Code:
    #include <stdio.h>
    int main()
    {
          int code;
          printf(“Enter the error code (1-3): “);
          scanf(“%d”,&code);
          switch(code)
          {
               case 1:
                    puts(“Drive Fault, not your fault.”);
                    break;
               case 2:
                    puts(“Illegal format, call a lawyer.”);
                    break;
               case 3:
                    puts(“Bad filename, spank it.”);
                    break;
               default:
                    puts(“That’s not 1, 2, or 3”);
          }
          return(0);
    }
    Then later it said in the next exercise to modify the source code so that it the user has to input letters A-C to get the output. I changed the code to this:
    Code:
    #include <stdio.h>
    
    int main()
    {
        int code;
        char 'A', 'B', 'C';
    
        printf("Enter the error code (A-C): ");
        scanf("%d",&code);
    
        switch(code)
        {
            case 'A':
                puts("Drive Fault, not your fault.");
                break;
            case 'B':
                puts("Illegal format, call a lawyer.");
                break;
            case 'C':
                puts("Bad filename, spank it.");
                break;
            default:
                puts("That's not A, B, or C.");
        }
        return(0);
    }
    But when I try to run it now, I get this error:
    C:\Users\Osman\Documents\BegC4D\ex0817\main.c|6|error: expected identifier or '(' before 'A'|
    Chapter 7 had the getchar() function and the %c placeholder, and for the current exercise, the book said to look back to Chapter 7 for a hint as to what to do and how. I'm thinking I might have to use %c and getchar somehow here, but I don't really how to make it work, so that's also something I'd like to ask here.

    Note: The indents aren't showing, but I did put them in.
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    159
    Rep Power
    19
    Note: The indents aren't showing, but I did put them in.
    That's because you used quote tags instead of code tags.

    Highlight your code then press the # icon to insert [code] Add code here. [/code] tags.


    Jim
    Last edited by jimblumberg; December 22nd, 2013 at 07:04 AM.
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Location
    Karachi, Pakistan
    Posts
    16
    Rep Power
    0
    Originally Posted by jimblumberg
    That's because you used quote tags instead of code tags.

    Highlight your code then press the # icon to insert [code] Add code here. [/code] tags.


    Jim
    Okay, I'll keep that in mind. Thanks for letting me know.

    But I'm still waiting for an answer to the new questions I asked in that post. [I'll edit it now to change the tags into code tags.]
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    159
    Rep Power
    19
    Look at this snippet:
    Code:
       char 'A', 'B', 'C';
    Is that how you declare variables? Don't you want a single character variable that can hold one of those letters?

    How about just changing your "code" variable to a char? Don't forget to modify your scanf() call to use the proper format specifier.

    Jim
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Location
    Karachi, Pakistan
    Posts
    16
    Rep Power
    0
    Originally Posted by jimblumberg
    Look at this snippet:
    Code:
       char 'A', 'B', 'C';
    Is that how you declare variables? Don't you want a single character variable that can hold one of those letters?

    How about just changing your "code" variable to a char? Don't forget to modify your scanf() call to use the proper format specifier.

    Jim
    What am I doing wrong now?

    Code:
    #include <stdio.h>
    
    int main()
    {
        int A;
        int B;
        int C;
    
        printf("Enter the error character (A-C): ");
        A = getchar();
        B = getchar();
        C = getchar();
        scanf("%c",&char);
    
        switch(char)
        {
            case A:
                puts("Drive Fault, not your fault.");
                break;
            case B:
                puts("Illegal format, call a lawyer.");
                break;
            case C:
                puts("Bad filename, spank it.");
                break;
            default:
                puts("That's not A, B, or C.");
        }
        return(0);
    }
    The error and warning messages I'm getting with this are like this:
    C:\Users\Osman\Documents\BegC4D\ex0817\main.c||In function 'main':|
    C:\Users\Osman\Documents\BegC4D\ex0817\main.c|13|error: expected expression before 'char'|
    C:\Users\Osman\Documents\BegC4D\ex0817\main.c|15|error: expected expression before 'char'|
    C:\Users\Osman\Documents\BegC4D\ex0817\main.c|7|warning: variable 'C' set but not used [-Wunused-but-set-variable]|
    C:\Users\Osman\Documents\BegC4D\ex0817\main.c|6|warning: variable 'B' set but not used [-Wunused-but-set-variable]|
    C:\Users\Osman\Documents\BegC4D\ex0817\main.c|5|warning: variable 'A' set but not used [-Wunused-but-set-variable]|
    ||=== Build finished: 2 errors, 3 warnings (0 minutes, 0 seconds) ===|
    What would be the best way to declare the variables A, B, and C here, firstly? And to also make sure it doesn't say that I declared them but didn't use them in the code?
  26. #14
  27. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,116
    Rep Power
    1803
    Originally Posted by DragonOsman2
    do understand everything else that's going in the rest of the code, too.
    Good, then you might want to explain how:
    Code:
    upper_case_answer = answer & (~ ' ');
    works. The variable name is a big clue to what it does, but given your lack of comprehension of even the most basic aspects of C, I would be amazed if you truely understood that. That said, I would not spend the time, it is an example of a somewhat dubious practice - clever code. Follow this advice from Brian Kernighan..

    Originally Posted by DragonOsman2
    Anyway, I have another question now.
    If you have another question, start another post; this will turn into a Tower of Babel if we start discussing more that one subject in a single thread.

    That said:
    Code:
        char 'A', 'B', 'C';
    These are not valid variable declarations, but you done need any more variables, the case labels are literal constants.

    Code:
        scanf("%d",&code);
    You are still asking for an integer when you want to process a char (%c is the correct format specifier, and the type of the variable "code" should ideally change).

    Code:
        return(0);
    The one thing that b49P23TIvg and I perhaps can agree on is that the parentheses here are misplaced - lots of people do it, most - including the authors of your book - probably could not tell you why! They are unnecessary; "return" is not a function call, it is a statement, syntax: return <expression>

    Originally Posted by DragonOsman2
    I'm thinking I might have to use %c and getchar somehow here
    No getchar() does not accept a format specifier, it is only for getting a character so does not need a format specifier. scanf() on the other hand can be used to input multiple types, so requires a format specifier to define intent. You need the %c where you currently have %d. Rather than relying on your book, you might research wider by reading the documentation for the function you use:

    Examples:
    http://www.cplusplus.com/reference/cstdio/scanf/

    http://www.cplusplus.com/reference/cstdio/getchar/
    Last edited by clifford; December 22nd, 2013 at 10:54 AM.
  28. #15
  29. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,931
    Rep Power
    481
    DragonOsman2 seems to confuse "run" with "compile".

    char 'A';
    is invalid c and shouldn't compile. That the program didn't run is true. DO2 didn't get that far. The program didn't compile.



    Yes, & (!' ') is stupid clever code. I just didn't feel like including ctypes or whichever header and looking in the manual for the case-changing macros or functions. I don't know their names off hand. I wouldn't use it if someone legitimate were paying me to write code, nor would I use it if I were expected to explain every secret.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo