Thread: If statment +text

  1. #1
    Registered User
    Join Date
    Dec 2001
    Posts
    367

    If statment +text

    I want to type in a text with the std::cin and then store it in a variable, like:

    char text[20];
    std::cin >> text;

    Then comes the problem, I want to use the if statement and depending on whatever you've typed in launch a specific action, like:

    if (text=="whatever") {std::cout << "this is some text";};
    else if (text=="I am old") {std::cout << "No, you're young";};
    else {std::cout << "Type in something else";};

    But it doesn't work out!


    Help me solve this!!!!!!!!!!!!

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Try the function strcmp(). It compares C Style strings and gives out 0 if they are both the same

  3. #3
    Unregistered
    Guest
    Code:
    #include <iostream>
    #include <stdlib.h>
    #include <string.h>
    using namespace std;
    
    int main(void)
    {
      char text[20];
      cin.getline(text, 20, '\n');
    
      if(strcmp(text, "whatever"))
        std::cout << "this is some text";
      else if(strcmp(text, "I am old"))
        std::cout << "No, you're young";
      else
        std::cout << "Type in something else";
      return EXIT_SUCCESS;
    }

  4. #4
    ¡Amo fútbol!
    Join Date
    Dec 2001
    Posts
    2,138
    that code won't work. strcmp returns 0 if true. therefore u have to type ! before every time u use it.

    ex. if (!strcmp(text,"whatever")
    {//do whatever}

  5. #5
    Registered User
    Join Date
    Jan 2002
    Posts
    4
    Convert the array 'text' to a string, and then compare.

    string answer;

    ie. answer = text;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My text doesn't display
    By joeprogrammer in forum Game Programming
    Replies: 11
    Last Post: 02-23-2006, 10:01 PM
  2. Appending text to an edit control
    By dit6a9 in forum Windows Programming
    Replies: 3
    Last Post: 08-13-2004, 09:52 PM
  3. Text positioning and Text scrolling
    By RealityFusion in forum C++ Programming
    Replies: 3
    Last Post: 08-13-2004, 12:35 AM
  4. Scrolling The Text
    By GaPe in forum C Programming
    Replies: 3
    Last Post: 07-14-2002, 04:33 PM
  5. Replies: 1
    Last Post: 07-13-2002, 05:45 PM