Thread: beginner question

  1. #1
    Registered User
    Join Date
    Jul 2007

    beginner question

    #include <iostream>
    #include <iomanip>
    using namespace std;
    int main()
    	char state[3];
    	cout << "Enter NC, SC, GA, FL, or AL. ";
    	cin >> state;
    	if (state == "nc" || state == "NC")
    		cout << "North Carolina.";
    	else cout << "That is an invalid choice.\n";
    When I input nc or NC, it does not output north carolina, but displays the invalid message. What did I do wrong? thanks

  2. #2
    The larch
    Join Date
    May 2006
    Char arrays cannot be compared with == because it will compare the addresses of the arrays (pointers) and not the array contents. Either use the strcmp function or std::string (which allows comparison with comparison operators).
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Registered User
    Join Date
    Jul 2007
    if ((strcmp(state, "nc") == 0) || (strcmp(state, "NC") == 0))
    strcmp() takes the two strings and compares them. The output is zero when they are equal.

  4. #4
    "I Win!" by U. Lose vart's Avatar
    Join Date
    Oct 2006
    Rishon LeZion, Israel
    so better to use std::string to avoid possible buffer overrun problems and simplify the string comparisons
    To be or not to be == true

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner: Linked List question
    By WeatherMan in forum C++ Programming
    Replies: 2
    Last Post: 04-03-2008, 07:16 AM
  2. Quick IF statement question (beginner)
    By jim.rattlehead in forum C Programming
    Replies: 23
    Last Post: 11-29-2007, 06:51 AM
  3. beginner question
    By Barrot in forum C++ Programming
    Replies: 4
    Last Post: 08-19-2005, 02:17 PM
  4. Question About External Files (Beginner)
    By jamez05 in forum C Programming
    Replies: 0
    Last Post: 08-11-2005, 07:05 AM
  5. Beginner on Win32 apps, lame question.
    By Templario in forum C Programming
    Replies: 3
    Last Post: 11-06-2002, 08:39 PM