在 C++ 中,可以使用 cin 和 cout 进行输入和输出。
cout的用法如下:
“待输出项”可以是各种基本类型的变量、常量和表达式。
以下程序演示了 cout 的用法:
- #include <iostream>
- using namespace std;
- int main(){
- int n = 5;
- double f = 3.9;
- char c = 'a';
- cout << "n=" << n << ",f=" << f << endl; //endl表示换行
- cout << 123 << ", c=" << c << endl;
- return 0;
- }
程序的输出结果是:
n=5,f=3.9
123, c=a
程序第 1 行引用了头文件 iostream,第 2 行表示使用名字空间 std,C ++ 程序通常都会包含这两行。如果没有语句using namespace std;,则 cout 就会没有定义,除非写明std::cout,指明其来自名字空间 std。
第7行输出了字符串、整型变量、浮点型变量。endl表示换行。
cin的用法如下:
以下程序演示了 cin 的用法:
- #include <iostream>
- using namespace std;
- int main(){
- int nl, n2;
- char s[20];
- double f;
- char c;
- cin >> s >> nl >> n2 >> c >> f ;
- cout << s <<"," << nl << "," << n2 << "," << c << "," << f <<endl;
- return 0;
- }
程序的运行结果:
Tom 5 10k 1.23↙
Tom,5,10,k,1.23
在本教程的运行结果中,↙表示按 Enter 键(回车键)。