user3150534
user3150534

Reputation: 23

C++: Displaying a Variable

I have a quick question about C++. I am making a text-based game and I want the player to be able to type in "Score" and it will print the current score (int score = 50). I am using if(Choice == 3) for numbers but I want to be able to type words into the input.

Can anyone help?

Thanks for reading.

Upvotes: 0

Views: 98

Answers (4)

Chris
Chris

Reputation: 2763

Try:

std::string userInput;

// Takes a string input from cin and stores in userInput variable
getline(std::cin, userInput);   

// Check if user input is "Score"
if (userInput.compare("Score") == 0)
{
    std::cout << "Score = " << score << std::endl;
}

If the user input is "Score" then the comparison will be an exact match, and userInput.compare() will return 0, which is why we check if its zero.

Upvotes: 0

Floris
Floris

Reputation: 46435

Bit hard to guess exactly what you are trying to do, but in general if you want to compare strings, you use string comparison routines. For example

#include <iostream>

int main(void) {
    std::string choice;
    std::cout<<"Please enter your choice:"<<std::endl;
    std::cin>>choice;
    if (choice.compare("score")==0) {
       std::cout << "score!" << std::endl;
    }
    else {
      std::cout << "fail!" << std::endl;
    }
}

If you use boost, you can do case insensitive comparison. Or you can cast the input to all lower case. Google "case insensitive string compare c++" for more information.

Upvotes: 0

Yam Marcovic
Yam Marcovic

Reputation: 8141

std::string input;
cin >> input;
// lowercase it, for case-insensitive comparison
std::transform(input.begin(), input.end(), input.begin(), std::tolower);

if (input == "score")
  std::cout << "Score is: " << score << std::endl;

Upvotes: 1

Christian Hackl
Christian Hackl

Reputation: 27538

Use std::getline to read a complete line into a string, then simply compare the string with ==.

There are many other ways to do this, but any solution not based on std::getline is probably needlessly complicated.

Upvotes: 0

Related Questions