Thread: if statements using strings as the condition

  1. #1
    Registered User
    Join Date
    Dec 2003
    Posts
    12

    if statements using strings as the condition

    OK, I am trying to ask the user to enter in a letter y. I am asking if the letter Y or y is entered, then print something. Its not working. Its executing the clause under the else.

    I tested this out by typing in Y or y and it keeps on printing out 'print - did not work'. How can I get it to print 'print - it worked' when I type in eitehr Y or y???

    Code:
    #include<stdio.h>
    
    void main()
    {
      char strBoolean[2];
      
      scanf("%s", strBoolean);
    
      if(strBoolean == 'Y' || strBoolean == 'y')
      {
       print("print - it worked");
      }
      else
      {
         printf("print - did not work");
      }
    }
    Regards,
    Trang

  2. #2
    Registered User
    Join Date
    Dec 2003
    Posts
    12

    correction to my previous code

    Correction - I tped it worng the first time. Here is what I put:

    Code:
    #include<stdio.h>
    
    void main()
    {
      char strBoolean[2];
      
      scanf("%s", strBoolean);
    
      if(strBoolean == 'Y' || strBoolean == 'y')
      {
         printf("print - it worked");
      }
      else
      {
         printf("print - did not work");
      }
    }
    Regards,
    Trang

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    1) void main is bad. Search the FAQ and the board to find out why.
    2) You can't compare the values of two strings using the == operator.
    3) To do what you need, #include <string.h> and change or if statement to:
    Code:
    if( strcmp(strBoolean, "Y") == 0 || strcmp(strBoolean, "y")== 0)
    4) An even better way for what you want to do is instead of a string use a single character and use getchar()
    5) fscanf is generally better for user input then scanf.

    edit: note the " " instead of ' ' around the Y. ' ' denotes a single character whlie " " denotes a string.

  4. #4
    Registered User
    Join Date
    Dec 2003
    Posts
    12

    Thank you

    Thank you so much. I used the include file string.h and used your suggested code and it worked.

    I researched in the faqs about the void main() and I understand why it isn't good practie to use voide main().

    I want to ask you about the getchar() and the fscanf though.

    First, what is the difference between scanf() and fscanf()?

    Secondly, can you explain a litttle bit about the getchar() function?
    Regards,
    Trang

  5. #5
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    getchar() gets a single character from the input stream and assigns it to the variable. So you can do:
    Code:
    #include <stdio.h>
    int main (void)
    {
      int ch;
    
      ch=getchar();
    
      if (ch == 'y' || ch == 'Y')
      /* rest of code */
    }
    The reason for int ch instead of char ch is because thats what getchar returns. C treats chars at short integers so the above comparison is legal.

    Actually I was wrong to use fscanf to get the input info. I meant fgets. This is a function to get a string from a stream. scanf has a problem if you input "yes" and also will leave the newline (think the character that is sent when you press enter) in the buffer. fgets will only get the number of characters allowed by the size and will also capture the newline character if there is room.

    Way to use it would be like this (for your program)
    Code:
    fgets ( strBoolean, sizeof(strBoolean), stdin)
    Do a search and you'll be able to find a lot more information about it, I think its in the FAQ also. Look for why gets is bad.

  6. #6
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>what is the difference between scanf() and fscanf()?
    scanf() reads from file stream stdin, which usual equates to keyboard input (or redirected input).
    fscanf() will read from a file stream you specify in your source.

    >>getchar()
    This reads one character from stdin (again, the keyboard normally).

    Look 'em up, over here: http://www.rt.com/man/

    .... beat
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  7. #7
    Registered User
    Join Date
    Dec 2001
    Posts
    44
    For trang:
    The way you're using scanf is dangerous. If the input is more than 1 character long, then you'll overwrite the array into which you're reading data. You need to specify the length of the string argument (%s) that you're asking scanf to read. In this case, 1 character.

    Also, you need to check the value returned by scanf. There's no guarentee that it has read anything meaningful. Try:

    Code:
    int status=0;
    
    do {
      /* print message asking for input */
      status=scanf("%1s",strBoolean);
      if (status==EOF) {
        /* error or end of file encountered - report the error and die */
      } else if (status!=1) {
         /* scanf didn't match anything sensible, the user probably typed nonsense. Say so */
      }
    } while (status!=1);
    As Thantos has said already:
    1) don't use voide main, or even void main.
    2) do use strcmp to compare strings, not == ...

    For explaination, a==b compares the values of a and b. In the case of strings, a and b are typically either pointers to char or array identifiers which 'decay' in that context to pointers to the first element (again, a pointer to char). For strings, these pointers point to the start of an array of characters terminated by a '\0' character. a==b then, would compare the value of the /pointers/ not the /contents/ of the strings. strcmp() on the other hand, compares the strings the pointers point to and returns 0 if the strings are the same.

    3) consider using getchar instead of scanf

    Getchar will read a single character from the standard input stream (stdin). The value returned is either EOF (when EOF or an error occurs IIRC) or the value of a character.

    The downside is that most C implimentations have buffered input on stdin. The user would typically be able to type a whole load of things - more than one character - and then enter. At that point, the C implimentation will handle your getchar and retrieve the first character. The rest of the characters entered by the user in the buffer will stay there until you read them. In that case, get your character and process it. Then, clear the input buffer by reading it in character by character until EOF occurs (there's no more characters) or a newline '\n' character is encountered.


    <snipped - query about fscanf, which thantos has clarified whilst I wasn't looking>

    Ian Woods

  8. #8
    Registered User
    Join Date
    Dec 2003
    Posts
    12
    Thank you so much. You guys helped me out a lot. This is awesome. You see I'm new to C. I'm taking a class on it and am doing an assignment.

    I'm so glad I found this forum, b/c the e-text that's provided for our class does'nt have anything about what you guys taught me.

    I'm sure I'll be back here w/ many more questions.

    Thanks again!!!
    Regards,
    Trang

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strings in C++
    By elad in forum C++ Programming
    Replies: 11
    Last Post: 05-20-2006, 02:27 AM
  2. Problems with strings as key in STL maps
    By all_names_taken in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2006, 11:34 AM
  3. cin strings till eof
    By bfedorov11 in forum C++ Programming
    Replies: 2
    Last Post: 10-15-2003, 07:27 AM
  4. Table mapping Strings to Strings
    By johnmcg in forum C Programming
    Replies: 4
    Last Post: 09-05-2003, 11:04 AM
  5. need a little help with if statements and strings
    By kes103 in forum C Programming
    Replies: 1
    Last Post: 03-20-2002, 12:08 PM