Thread: If String Help

  1. #1
    Registered User
    Join Date
    Sep 2010
    Location
    Portugal
    Posts
    22

    If String Help

    Hey everybody, hadn't came here in a while, but i just got stuck:


    Code:
    #include <stdio.h>
    
    int main(void)
    {
        char answer[0];
        
        printf("\nWhich formula do you want to use?\n");
        scanf("%s", answer);
        
        if (answer=="a")
        {
            printf("You chose a!");
                                   
        }
        else
        {
            printf("Else!!!");
            }
        getchar();
        return 0;
    
    }
    Even when I type "a", it returns "Else!!!". What's the problem with this?

  2. #2
    Registered User
    Join Date
    Sep 2010
    Location
    Portugal
    Posts
    22
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        char answer[0];
        char formula1[1] = "a";
        
        printf("\nWhich formula do you want to use?\n");
        scanf("%s", answer);
        
        if (answer==formula1)
        {
            printf("You chose a!");
                                   
        }
        else
        {
            printf("Else!!!");
            }
        getchar();
        return 0;
    
    }
    This doesn't work either, soz for double post, but it makes sense here.

  3. #3
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    use strcmp() from string.h.
    go and read documentation before asking any question about how to use function!

  4. #4
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    char answer[0] doesn't make any sense, and neither does any array of chars of length less than 2. In order to have something treated as a string you need to have the string terminator character '\0' at the end of your array. So an array of size 2 will only be able to hold one actual character and the string terminator. An array of size 1 can only be the empty string "\0".

    String comparison in C is not done via == but via strcmp(). Google for that function and learn how to use it.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  5. #5
    Registered User
    Join Date
    Sep 2010
    Location
    Portugal
    Posts
    22
    Quote Originally Posted by Bayint Naung View Post
    use strcmp() from string.h.
    go and read documentation before asking any question about how to use function!
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        char answer[0];
        
        printf("Welcome to Formulum!\n");
        printf("\nWhich formula do you want to use?\n");
        scanf("%s", answer);
        
        if (!strcmp(answer,"a"))
        {
            printf("You chose a!");
                                   
        }
        else
        {
            printf("Else!!!");
            }
        getchar();
        return 0;
    
    }

    Works great thanks!

  6. #6
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    I think OP is using gcc. gcc accepts such kind of thing...
    Anyway I suggest that OP uses either C89 or C99.
    gcc -std=c89 -Wall -pedantic-errors source.c # or -std=c99 for C99

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You still should not be writing:
    Code:
    char answer[0];
    This use of a zero length array may be allowed as a compiler's language extension, but is otherwise illegal, and is not intended to be used like this anyway. Rather, put a number greater than 1 (since you also need to account for the null character).
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User
    Join Date
    Sep 2010
    Location
    Portugal
    Posts
    22
    Quote Originally Posted by laserlight View Post
    You still should not be writing:
    Code:
    char answer[0];
    This use of a zero length array may be allowed as a compiler's language extension, but is otherwise illegal, and is not intended to be used like this anyway. Rather, put a number greater than 1 (since you also need to account for the null character).
    So how do I make it work for like infinite characters, since I don't know what the user is gonna write, for example: user's name.

  9. #9
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    You have to use dynamic memory allocation.malloc,realloc,calloc,free.
    But i think you should master pointer,array,etc first...

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Use fgets rather than scanf: SourceForge.net: Scanf woes - cpwiki
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    The Dragon Reborn
    Join Date
    Nov 2009
    Location
    Dublin, Ireland
    Posts
    629
    Hey I maybe a noob but maybe I can help with this one.


    char answer=="a"

    you are comparing a string when it should be 'a'

    a string is an array of characters, and when you store a string - they are divided into characters

    so if i had
    char answer[6] = "Hello" ;
    it will be like this in memory
    'H' 'e' 'l' 'l' 'o' '\0'
    Notice that although the length of hello is 5 characters long, I am declaring the variable answer as having 6 elements, because a string of char type in C/C++ must be terminated by a null character.

    so when you did
    char answer[0] ="a"
    number one that is redundant.

    Why do that, when you can simply do char
    answer = 'a' ?
    also when you initialize
    char answer[0]="a"
    I am surprised that even compiled..the compiler should have told you to declare at least one element, I know this without compiling it, because I did the same thing last year
    If you had declared more than one element for answer, then your if statement should have worked.

    strcmp should have worked as well

    Since others have provided a code for strcmp. I wouldn't
    but I hope my explanation on how strings are stored in memory helped .

  12. #12
    The Dragon Reborn
    Join Date
    Nov 2009
    Location
    Dublin, Ireland
    Posts
    629
    Quote Originally Posted by ScoutDavid View Post
    So how do I make it work for like infinite characters, since I don't know what the user is gonna write, for example: user's name.
    Well, the thing is you can't unless you know the length of the maximum string you want to store.

    you could do this of course.

    char answer[] = "a"
    and that would automatically put in a null character for you.

    but let say later you want to use a strcat() function to add a string to the array
    answer? Well you can't because the length is already defined.
    You will get a compiler error or warning at least.

    The only way is either to declare a massive amount of element if you are lucky to have enough memory.
    Or use dynamic memory allocation - although I haven't tried that yet...

    But one thing.. if you start using strings with C++
    there is a class called string, to declare string objects.

    It is a beauty, and you rarely have to worry about string length, and you never have to worry about the null character!

  13. #13
    Registered User
    Join Date
    Sep 2010
    Location
    Portugal
    Posts
    22
    Quote Originally Posted by Eman View Post
    Hey I maybe a noob but maybe I can help with this one.


    char answer=="a"

    you are comparing a string when it should be 'a'

    a string is an array of characters, and when you store a string - they are divided into characters

    so if i had
    char answer[6] = "Hello" ;
    it will be like this in memory
    'H' 'e' 'l' 'l' 'o' '\0'
    Notice that although the length of hello is 5 characters long, I am declaring the variable answer as having 6 elements, because a string of char type in C/C++ must be terminated by a null character.

    so when you did
    char answer[0] ="a"
    number one that is redundant.

    Why do that, when you can simply do char
    answer = 'a' ?
    also when you initialize
    char answer[0]="a"
    I am surprised that even compiled..the compiler should have told you to declare at least one element, I know this without compiling it, because I did the same thing last year
    If you had declared more than one element for answer, then your if statement should have worked.

    strcmp should have worked as well

    Since others have provided a code for strcmp. I wouldn't
    but I hope my explanation on how strings are stored in memory helped .
    Thanks much!


    However, I still have a doubt:

    Code:
    while (!strcmp(answer,password))
        {
            printf("Wrong Password");
            scanf("%s", answer);
              
        }
    This does: "while answer equals password"
    How do i do: "while answer isn't equal to password"??

    Thank you in advance!

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Personally, for "while answer equals password", I suggest:
    Code:
    while (strcmp(answer, password) == 0)
    {
        printf("Wrong Password");
        scanf("%s", answer);
    }
    The "==" provides a visual hint that you are comparing the strings for equality. Thus, the code for "while answer isn't equal to password" is obviously:
    Code:
    while (strcmp(answer, password) != 0)
    {
        printf("Wrong Password");
        scanf("%s", answer);
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    For isn't equal, I would change laserlight's == into !=.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  3. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM