请从键盘输入学号,姓名,年龄,体重,以四种方式输出
时间: 2023-05-22 15:01:47 浏览: 142
学号XXX姓名C语言实验2输入输出1
5星 · 资源好评率100%
你好,我是 C知道,很高兴为您解答问题。以下是您提出的问题的答案:
请从键盘输入学号,姓名,年龄,体重,以四种方式输出:
1. 使用 printf 函数输出:
```
#include <stdio.h>
int main() {
int student_id, age;
char name[20];
float weight;
printf("请输入学号:");
scanf("%d", &student_id);
printf("请输入姓名:");
scanf("%s", name);
printf("请输入年龄:");
scanf("%d", &age);
printf("请输入体重:");
scanf("%f", &weight);
printf("学号:%d,姓名:%s,年龄:%d,体重:%.2f\n", student_id, name, age, weight);
return 0;
}
```
2. 使用 cout 函数输出:
```
#include <iostream>
using namespace std;
int main() {
int student_id, age;
char name[20];
float weight;
cout << "请输入学号:";
cin >> student_id;
cout << "请输入姓名:";
cin >> name;
cout << "请输入年龄:";
cin >> age;
cout << "请输入体重:";
cin >> weight;
cout << "学号:" << student_id << ",姓名:" << name << ",年龄:" << age << ",体重:" << weight << endl;
return 0;
}
```
3. 使用 fprintf 函数输出到文件:
```
#include <stdio.h>
int main() {
int student_id, age;
char name[20];
float weight;
printf("请输入学号:");
scanf("%d", &student_id);
printf("请输入姓名:");
scanf("%s", name);
printf("请输入年龄:");
scanf("%d", &age);
printf("请输入体重:");
scanf("%f", &weight);
FILE *fp;
fp = fopen("output.txt", "w");
fprintf(fp, "学号:%d,姓名:%s,年龄:%d,体重:%.2f\n", student_id, name, age, weight);
fclose(fp);
return 0;
}
```
4. 使用 ofstream 函数输出到文件:
```
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int student_id, age;
char name[20];
float weight;
cout << "请输入学号:";
cin >> student_id;
cout << "请输入姓名:";
cin >> name;
cout << "请输入年龄:";
cin >> age;
cout << "请输入体重:";
cin >> weight;
ofstream outfile("output.txt");
outfile << "学号:" << student_id << ",姓名:" << name << ",年龄:" << age << ",体重:" << weight << endl;
outfile.close();
return 0;
}
```
希望这些答案能够帮助到您,如果您还有其他问题,请随时提出。
阅读全文