C ++各个数据类型的输入输出

发布时间 2023-04-22 12:43:51作者: linux星

C++中各个数据类型的输入输出主要使用iostream库和格式化输入输出函数printfscanf等,下面是各个数据类型的输入输出方式:

1.整型:使用cincout进行输入输出,或者使用scanfprintf进行输入输出。

int n;
cin >> n;
cout << n << endl;
scanf("%d", &n);
printf("%d\n", n);

2.浮点型:使用cincout进行输入输出,或者使用scanfprintf进行输入输出。

double d;
cin >> d;
cout << d << endl;
scanf("%lf", &d);
printf("%lf\n", d);

3.字符型:使用cincout进行输入输出,或者使用scanfprintf进行输入输出。

char c;
cin >> c;
cout << c << endl;
scanf("%c", &c);
printf("%c\n", c);

4.字符串:使用cincout进行输入输出,或者使用scanfprintf进行输入输出。

string s;
cin >> s;
cout << s << endl;
scanf("%s", s.c_str());
printf("%s\n", s.c_str());

5.数组:使用循环结构和cincout进行输入输出,或者使用循环结构和scanfprintf进行输入输出。

int a[10];
for (int i = 0; i < 10; i++) {
    cin >> a[i];
    cout << a[i] << " ";
}
printf("\n");
for (int i = 0; i < 10; i++) {
    scanf("%d", &a[i]);
    printf("%d ", a[i]);
}
printf("\n");

6.结构体:使用结构体对象和cincout进行输入输出,或者使用结构体对象和scanfprintf进行输入输出。

struct student {
    string name;
    int age;
};
student s;
cin >> s.name >> s.age;
cout << s.name << " " << s.age << endl;
scanf("%s %d", s.name.c_str(), &s.age);
printf("%s %d\n", s.name.c_str(), s.age);