⒉ 输出

讲完框架,我们就来说一下输出。

C++ 的输出有非常多种。我会逐一介绍。

cout 语句

这是 C++ 语言最常用的输出语句了,语法为:

cout<<a<<b<<c<<d;
//"<<" 表示插入符,a、b、c、d 表示要输出的东西

比如我们输出 Hello world! 就可以写为 cout<<"Hello world!"

注意!cout<<"Hello world!" 这里我用了双引号 ",那是因为双引号会把包含在内的内容毫无更改地输出出来。如果你这样输出:cout<<"1+1",结果就会是 1+1;而如果你这样输出:cout<<1+1,结果就会是 \(1+1\) 的值 \(2\)

来练一道题。

输出 100+1000= 和它所等于的值。

#include<iostream>
using namespace std;
int main(){
	cout<<"100+1000="<<100+1000;//前面,把"100+1000="直接输出,后面,将 100+1000 的值 1100 输出出来了。
	return 0;
}

我们还可以这么写:

#include<iostream>
using namespace std;
int main(){
	cout<<100/*100 算出来的结果是 100*/<<'+'/*单引号只能往里塞单个字符*/<<1000<<'='<<100+1000;//后面的上面有,不重复解释
	return 0;
}

另外,cout 不会自动换行。比如:

cout<<1;
cout<<2;

会输出

12

需要

cout<<1<<endl;
cout<<2;

cout<<"1\n";
cout<<2;

才能输出

1
2

printf 语句

printf 语句 C++ 不常用,主要用于 C 语言。学习这个主要是 cout 语句比它慢,当数据很大的时候,我们用的。

printf 需要用到库 cstdiostdio.h,且它不用命名空间。

用它输出 100+1000= 和它所等于的值,可以这么写:

#include<stdio.h>
int main(){
	printf("100+1000=%d",100+1000);
	return 0;
}

用它输出换行符 \n

printf("\n");

putchar 语句

putchar 是用来输出单个字符的,需要用到库 cstdiostdio.h,且它不用命名空间。
比如我们可以 putchar('1'),putchar('\n'),putchar('A'),输出

1
A
#include<stdio.h>
int main(){
	putchar('1'),putchar('\n'),putchar('A');
	return 0;
}

puts 语句

puts 是用来输出字符串的,需要用到库 cstdiostdio.h,还需用到 cstringstring.h 库,且它不用命名空间。注意!puts 语句末尾自带换行!
我们 puts("Hello world!") 相当于 cout<<"Hello world\n",都是输出

Hello world!

#include<stdio.h>
#include<string.h>
int main(){
	puts("Hello world!");
	return 0;
}
posted @ 2025-04-05 20:56  longyitongxue  阅读(130)  评论(1)    收藏  举报
名言与时间展示页

© 2024 名言展示页