Home > Enterprise >  How do i make different responses to different user inputs?
How do i make different responses to different user inputs?

Time:11-05

I'm a beginner, so please excuse my silly mistakes.

I'm trying to get a specific output when I input a specific name using strings, but I keep getting an error that my name wasn't declared in the scope. I also want to be able to add different responses for different inputs.

I tried looking up how to use strings, and I tried all sorts of combinations, but I'm still confused as to what I did wrong.

I'm sorry if this doesn't make sense, I'm just really bad at explaining things.

#include <iostream>
#include <cmath>
#include <string>

int main() {

    std::string firstname;
    
    std::cout << "please state your name. \n";
    std::cout << firstname;
    std::cin >> firstname;

    if (firstname == leo) {
        std::cout << "oh, you.";
    }
    
    return 0;
}

CodePudding user response:

First, std::cout << firstname; is a no-op since firstname is empty at that point.

Second, there is no name in your code. Is the error referring to leo? That should be wrapped in double-quotes since you meant it to be a string literal, not a variable.

Try something more like this:

#include <iostream>
#include <string>

int main() {

    std::string firstname;
    
    std::cout << "please state your name. \n";
    std::cin >> firstname;

    if (firstname == "leo") {
        std::cout << "oh, you.";
    }
    else {
        std::cout << "hello, " << firstname;
    }
    
    return 0;
}
  • Related