Home > Software engineering >  How do I insert user input variables into same spot in vector<string>?
How do I insert user input variables into same spot in vector<string>?

Time:10-28

//Main driver

int main(){

//If I run the code below.

    vector<string> A = {"My name is Muzaib.\n Hello"};
    cout << A[0];

//It will print My name is Muzaib

// Hello

//But what I want to know is how do I do the same but with user input?

string name, age;
cout << "Enter name: ";
getline(cin,name);
cout << "\nEnter age: ";
getline(cin,age);
vector<string> B = {"name \n age"}  //remember I want it in the same spot.
cout << B[0]

​ return 0; }

CodePudding user response:

It seems to me like you want to build a string from name '\n' age, so:

std::vector<std::string> B = {name   '\n'   age};

I recommend storing the name and age as separate entities though. Example:

struct foo {
    std::string name;
    int age;
};

std::ostream& operator<<(std::ostream& os, const foo& f) {
    return os << f.name << '\n' << f.age;
}

std::vector<foo> B = {{name, std::stoi(age)}};
std::cout << B[0] << '\n';
  • Related