1.5.4 情景应用4--在控制台接收用户输入的用户名
视频讲解:光盘\mr\01\lx\在控制台接收用户输入的用户名.exe
实例位置:光盘\mr\01\qjyy\04
基于控制台的应用程序,不仅能够进行输出,也可接收来自用户的输入信息。下面就来编写一个可以接收用户输入用户名的控制台应用程序。
新建一个基于控制台的应用程序,工程名为GetName。在工作区窗口中选择ClassView选项卡,展开GetName/Globals节点,双击其下的main节点,自动跳转到代码编辑窗口。在main函数中编写如下代码:
- #include "stdafx.h"
- #include "iostream.h"
- #include <iomanip.h>
- #include "string.h"
- int main()
- {
- char Username[10];
- char Password[10];
- cout << "请输入用户名:\n";
- cin >> Username;
- cout << "请输入密码:\n";
- cin >> Password;
- cout << "╔═════════════════╗\n";
- cout << "║ 登录框 ║\n";
- cout << "╠════════╦════════╣\n";
- cout << "║ 用户名: ║ " << Username
<< setw(13-strlen(Username)) << "║\n"; - cout << "╠════════╬════════╣\n";
- cout << "║ 密 码: ║ " << Password
<< setw(13-strlen(Password)) << "║\n"; - cout << "╚════════╩════════╝\n";
- return 0;
- }
运行程序,用户按要求输入用户名和密码,按Enter键确认,结果如图1.49所示。
|
| 图1.49 在控制台接收用户输入的用户名 |
DIY:在字符串中插入空格。(20分)(光盘\mr\01\qjyy\04_diy)
提示:使用setw函数在输出字符串时,在指定位置插入指定数量的空格。