简体   繁体   English

我的基本零初始化代码有问题吗?

[英]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而我今年 19 岁
  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而我今年 19 岁
  4. Who are you?你是谁?
  5. [user enters whatever] [用户输入任何内容]
  6. You are 0?你是0?

Edit: enter image description here编辑:在此处输入图像描述

You declared y as an integer.您将 y 声明为整数。 This means y can only be used to contain a number.这意味着 y 只能用于包含数字。 In your case, you want a to contain a std::string.在您的情况下,您希望 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;因此,只需将int y{}更改为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.并且不要忘记在 C++ 中您只能声明一次变量,因此您必须删除 y 的声明之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM