0

I am trying to learn C++. I created a program that inputs a name and then says "Hello, <name>!". But when I enter "Aditya Singh" as the name, it outputs "Hello, Aditya!", which is not what I expected.

My code:

#include <iostream>
#include <string>

using namespace std;

// I created the class because I was learning C++ Classes
class MyClass {
public: 
    void setName(string inp) {
        name = inp;
    }
    string getName() {
        return name;
    }

private:
    string name;
};

int main() {
    // Input Name

    string inpName;
    cout << "Please enter your name\n";
    cin >> inpName;

    // Say hello

    MyClass name;
    name.setName(inpName);
    cout << "Hello, " << name.getName() << "!" << endl;
}

Does this happen because of a white space in the string? How can I output a string with a white space then?

1 Answers1

1

This is because cin >> inpName reads a word at a time, so yes, it is because of the whitespace within the input. It seems what you need is a mechanism to read until the newline character \n. This functionality is already there, just replace cin >> inpName by

std::getline(cin, inpName); // Store everything until \n in inpName
lubgr
  • 37,368
  • 3
  • 66
  • 117