Search code examples
c++c++17zero-initialization

is there something wrong with my basic zero initialization code?


#include <iostream>
int main()
{

int x{ 19 };
std::cout << "Hola!" << '\n';
std::cout << "Me llamo Kay\n";
std::cout << "And I am " << x << " years old\n";
std::cout << "Who are you?\n";
int y{};
std::cin >> y;
std::cout << "You are " << y << "?" << '\n';
return 0;
}

So i want the code to run a program that goes:

  1. Hola!
  2. Me llamo Kay
  3. And I am 19 years old
  4. Who are you?
  5. [user enters whatever]
  6. You are [user entered]?

But instead what I get is:

  1. Hola!
  2. Me llamo Kay
  3. And I am 19 years old
  4. Who are you?
  5. [user enters whatever]
  6. You are 0?

Edit: enter image description here


Solution

  • You declared y as an integer. This means y can only be used to contain a number. In your case, you want a to contain a std::string. This means any kind of text, like the text the user has entered. So simply change int y{} into std::string y;. And don't forget you can only declare a variable once in c++, so you'll have to remove one of the declarations for y.