beginner question

This is a discussion on beginner question within the C++ Programming forums, part of the General Programming Boards category; Code: #include <iostream> #include <iomanip> using namespace std; int main() { char state[3]; cout << "Enter NC, SC, GA, FL, ...

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    4

    beginner question

    Code:
    #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
    Posts
    3,573
    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
    Posts
    36
    Code:
    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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    so better to use std::string to avoid possible buffer overrun problems and simplify the string comparisons
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

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, 08: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, 03:17 PM
  4. Question About External Files (Beginner)
    By jamez05 in forum C Programming
    Replies: 0
    Last Post: 08-11-2005, 08: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

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