Thread: check if user input matches a word

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    1

    Unhappy check if user input matches a word

    I need to know how to check if something a user inputs matches a word. For example, if the program asks "Do you want to continue?" and the user enters either "yes" or "no" it'll check to see if "yes" was entered then do something and same with "no". I can do this with numbers like "Enter 1 for Yes 0 for No" and with single letters like y and n but I can't figure out how to do this with entire words.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    The preferred method is to use C++ string objects:
    Code:
    #include <iostream>
    #include <string>
    
    std::cout<<"Do you want to continue? (yes/no): ";
    
    std::string s;
    std::getline(std::cin, s);
    
    if (s == "yes")
      continue;
    else
      break;
    You can also use the "poor man's strings", but then you end up having to use strcmp:
    Code:
    #include <cstring>
    #include <iostream>
    
    std::cout<<"Do you want to continue? (yes/no): ";
    
    char s[BUFSIZ];
    std::cin.getline(s, sizeof s);
    
    if (std::strcmp(s, "yes") == 0)
      continue;
    else
      break;
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 04-03-2008, 09:07 PM
  2. User determined input question
    By lyoncourt in forum C Programming
    Replies: 8
    Last Post: 09-30-2007, 06:10 PM
  3. SSH Hacker Activity!! AAHHH!!
    By Kleid-0 in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 03-06-2005, 03:53 PM
  4. Nested Structures - User Input
    By shazg2000 in forum C Programming
    Replies: 2
    Last Post: 01-09-2005, 10:53 AM
  5. Error checking user input
    By theharbinger in forum C++ Programming
    Replies: 5
    Last Post: 07-22-2003, 09:57 AM