具有用户输入的控制台 UI

Console UI with User input

本文关键字:控制台 UI 输入 用户      更新时间:2023-10-16

所以我正在尝试制作一个简单的控制台应用程序,要求用户提供某些特征。第一个问题,询问用户的年龄。例如,它应该看起来像"我>进入年龄

#include <iostream>
#include <string>
using namespace std;
//Variables
int Age;
 //Functions
int AgeEnt(){
cin >> Age;
return Age;
}
//Main
int main (){
    cout << "Welcome! Please enter  your age to continuen";
    cout << "I am " << AgeEnt << "    years old";
return 0;
}

这会自动将 1 放在年龄应该的位置。我将如何到达可以在文本之间输入数字的位置?我仍然是初学者,所以如果这在控制台中是不可能的,或者非常贬值,请原谅我。

int main (){
cout << "Welcome! Please enter  your age to continuen";
int age;
cin >> age;
return 0;
}

另外,为什么要在 main 上方声明函数和变量?除全局函数外,这在C++中不需要

#include <iostream>
using namespace std;
//Functions
int AgeEnt(){
    int Age;
    cin >> Age;
    return Age;
}
//Main
int main (){
    cout << "Welcome! Please enter  your age to continuen";
    AgeEnt();
    cout << "I am " << AgeEnt() << "    years old";
    return 0;
}

几件事

  1. 为此,您不需要<string>头文件。它没有在任何地方使用。
  2. 无需将Age声明为全局变量。它只在一个函数中使用,所以在其中声明它。

另外,虽然我在这里没有做过,但我通常会做一些类似int a = AgeEnt(); cout<<a;