Thread: How to check if char = "wateva"

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    28

    How to check if char = "wateva"

    hi,

    in my program it asks the user a question, the answer the user types is in a word format not a number or digit(eg: Twenty not 20)
    The problem is i dont know how to check weather the answer the user typed is correct..heres the code

    Code:
    #include <iostream.h>
    main()
    {
         char answer[50];
         cout<<"How many apples did i buy?: ";
         cin.getline(answer,50)
         
         if (answer == twenty)
         {
                    cout<<"Correct!";
         }
         std::cin.ignore();
         return 0;
         }

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Use strings instead if you're going to bother with C++, really, because they have that == operator at the ready for use. Also, iostream.h makes your compiler look old. Dump that bad habit and use current stuff: you probably need a better compiler.

    The user won't write out a number like that unless you tell them to.
    Code:
    // An improved version of the program! ^_^ Good mood...
    #include <iostream>
    #include <cctype>
    #include <string>
    #include <algorithm>
    
    int main (void) {
       std::string answer = "twenty";
       std::cout << "How many apples did I buy? (word answers):";
       std::cin >> answer;
       // This dandy little algorithm transforms a string based on the
       // predicate. I turned everything lower case to make sure it 
       // matches.
       transform(answer.begin(), answer.end(), answer.begin(), ::tolower);
    
       if(answer != "twenty")
       {
           std::cout << "Sorry, you're wrong\n";
       }
       else 
       {
           std::cout << "Yes, that's correct\n";
       }
       return 0;
    }

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    28
    thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  2. Obtaining source & destination IP,details of ICMP Header & each of field of it ???
    By cromologic in forum Networking/Device Communication
    Replies: 1
    Last Post: 04-29-2006, 02:49 PM
  3. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  4. comparing fields in a text file
    By darfader in forum C Programming
    Replies: 9
    Last Post: 08-22-2003, 08:21 AM