我需要 c++ 方面的帮助

I need help in c++

本文关键字:帮助 方面 c++      更新时间:2023-10-16

im 创建我喜欢称之为复杂 hello 世界的东西。 我对编码非常陌生,更不用说C ++了,为了开始,我创建了一个Hello World。 我现在知道如何轻松地做到这一点,所以我决定尝试做一些更复杂的事情。我希望我的程序首先询问"你想看你好世界吗?"然后根据用户输入"是"或"否",它将响应"hello world"或关闭程序。我以为我可以为此使用布尔值,但我卡住了。我需要知道如何创建一个代码来读取用户键入的内容,例如"yes",然后输出hello world。

喜欢:

if (the user"s answer) = yes cout << "Hello world!" << endl;
您需要

使用类似 std::cin 的东西来接受用户输入。使用类似std::string容器的东西来保存字母答案,即是或y。然后对照控件检查输入并有条件地打印 Hello World。

#include <iostream>
#include <string>
int main()
{
    std::string ans;
    std::cout << "Would you like to see the "Hello World"?n-> ";
    std::cin >> ans;
    if (ans == "yes" || ans == "y")
    {
        std::cout << "nHello World!" << std::endl;
    }
    return 0;
}

我们可以通过使用 c++ 提供的iostream来做到这一点。有两种方法可以做到这一点,使用 scanfcin 作为输入,但为了简单起见,我们只使用 cin .

#include <iostream>
using namespace std;
int main() {
    cout<<"Would you like to see the hello world?n";
    string answer;
    cin>>answer;
    if(answer=="Yes") cout<<"Hello, world!";
}

说明:我们使用 cout 提示用户,然后使用 string,我们检查输入是否等于 Yes ,如果是,则输出Hello, world!否则,代码将终止。您看到的n是用于制作新行,只是为了更清晰的格式。