Hi everyone..Testing strings and if question

This is a discussion on Hi everyone..Testing strings and if question within the C++ Programming forums, part of the General Programming Boards category; Hello all, What is wrong with this code? I can't get Wow! to print if the user answers "truck." Code: ...

  1. #1
    Registered User
    Join Date
    Jun 2005
    Posts
    27

    Question Hi everyone..Testing strings and if question

    Hello all,
    What is wrong with this code? I can't get Wow! to print if the user answers "truck."

    Code:
    #include <iostream>
    using namespace std;
    
    main()
    {
    char veh[6];
    
    cout << "Do you drive a car or a truck?" << "\n";
    cin >> veh;
    
    if(veh == "truck")
       {cout << "Wow!" <<  "\n";}
    
    return 0;
    }

  2. #2
    FOX
    Join Date
    May 2005
    Posts
    188
    That's not how you compare strings. Use strcmp instead.

  3. #3
    C/C++Newbie Antigloss's Avatar
    Join Date
    May 2005
    Posts
    212
    Code:
    if( !strcmp(veh, "truck") ) /* strcmp returns 0 if veh equals to "truck" */
        cout << "Wow!" <<  "\n";

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    27
    So what CAN I compare in an "if" statement?

  5. #5
    FOX
    Join Date
    May 2005
    Posts
    188
    veh is the address of the first element in the array.
    "truck" is the address of the first element in another character array, stored somewhere in read-only memory. So what you're really doing is comparing two different addresses, and not the strings as you might think.

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    27
    You're a genius! Thank you, I appreciate it a lot.

  7. #7
    Dae
    Dae is offline
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Location
    Canada
    Posts
    1,034
    Char strings require special treatment when comparing (that function stated in the posts above).

    However if you used the C++ string that come in the namespace std you can compare it the simple why used in your example. Just use "string veh;" instead of "char veh[6];"
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

  8. #8
    Registered User
    Join Date
    May 2005
    Location
    Toronto, Canada
    Posts
    257
    This tutorial helped me with strings.

Popular pages Recent additions subscribe to a feed

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