一、cin
//C++语言
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string>
using namespace std;
int main(){
// char name[30];
// scanf("%s", name); //不安全
// printf("name = %s\n", name);
// gets(name); //不安全
// printf("name = %s\n", name);
// fgets(name, 30, stdin); //安全,但只读取输入的29个字符,第30个字符是'\0'
// printf("name = %s\n", name);
// cin >> name; //不安全
// cout << name << endl;
string name;
cin >> name;
cout << name << endl;
}
C++中的cin, cout 均是类对象,C中的scanf和printf均是函数。
其中scanf, gets, fgets ,包括cin均是不安全的, 当输入大于29个字符时,全部运行时出错,其重点在于char name[30];的定义是不安全的,使用string类型(C++新增类型,C中没有string), string是个类, 是非常强大,也是足够安全的,最多能够存储1073741820个字符(通过name.max_size()可查看),几乎可以说是绝对安全的。
二、cout
//C++语言
#include<iostream>
#include<iomanip>
#include<stdio.h>
using namespace std;
int main(){
int a = 12345;
float b = 1234.567;
printf("--------c---------\n");
printf("%d\n", a); //12345
printf("%8d\n", a); // 12345(右对齐,三个空格填充)
printf("%-8d\n", a); //12345 (左对齐,三个空格填充)
printf("%f\n", b); //1234.567017(浮点型默认输出6位小数)
printf("%.2f\n", b); //1234.57 (保留两位小数)
printf("%10.2f\n", b); // 1234.57(10位有效数字,左边三个空格填充,保留两位小数)
cout << "------c++----------" << endl;
cout << a <<endl; //12345
cout << setw(8) << a << endl; // 12345(右对齐,左边三个空格)
cout << setiosflags(ios::left) << setw(8) << endl; //12345 (左对齐,右边三个空格)
cout << setfill('x') << setw(8) << a << endl; //xxx12345
cout << b << endl; //1234.57(c++默认6位有效数字)
cout << setprecision(3) << setiosflags(ios::fixed) << b <<endl; //1234.567
cout << setw(10) << setprecision(3) << setiosflags(ios::fixed) << b << endl; // 1234.567(右对齐,左边里两个空格填充)
}
注意:以上代码不存在前后逻辑关系,当成单句输出,忽略前后干扰现象