0

I have this (I've just started to learn btw):

#include <iostream> #include <string> using namespace std; int main() { string mystr; cout << "Welcome, what is your name? "; getline(cin, mystr); cout << "Nice to meet you, " << mystr << endl; cout << "May i call you 1 for short? (y/n)" << endl; getline(cin, mystr); } 

I want to next say;

cout << "Thank you, 1" << endl; 

OR:

cout << "Well ok, " << mystr << endl; 

... based on whether or not the user has typed y or n. How would i go about this? I've had a look around but i don't really know how to word it. I'm using Visual Studio Express and it is a console application.

2
  • Have you ever heard of the if statement? Commented Apr 12, 2014 at 12:09
  • I was thinking it would be something like that. Commented Apr 12, 2014 at 12:12

2 Answers 2

2

For a very simple way:

if (mystr == "1") { // ... } 

But you should accustom yourself to more error checking, so check the state of the stream after getline:

getline(cin, mystr); if (cin) { if (mystr == "1") { // ... } } else { // error } 

And of course, you may want to support any number in the future, not just 1. Then you need to convert the input string to a number. See std::stoi if you use C++11, or look at the thousands of past Stackoverflow questions about string-to-number conversions :)


Edit: Just noticed that you actually wanted to check for "y". Well, that's the same then:

if (mystr == "y") { // ... } 
Sign up to request clarification or add additional context in comments.

Comments

1

You should use if-else statement. For example

#include <cctype> //... std::string name = mystr; std::cout << "May i call you 1 for short? (y/n)" << std::endl; std::getline( std::cin, mystr ); for ( char &c : mystr ) c = std::tolower( c ); if ( mystr == "y" ) { name = "1"; std::cout << "Thank you, " << name << std::endl; } else { std::cout << "Well ok, " << name << std::endl; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.