C++ //习题13.6 在例13.17的基础上,修改程序,将存放在c数组中的数据读入并显示出来。

2024-01-03 01:05:22

C++程序设计 (第三版) 谭浩强 习题13.6

习题13.6 在例13.17的基础上,修改程序,将存放在c数组中的数据读入并显示出来。

IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。

?

代码块:
使用指针,函数的模块化设计
#include <iostream>
#include <strstream>
#include <string>
using namespace std;

const int N = 3;

typedef struct Student{
	char name[20];
	int num;
	double score;
}Student;

void initialStu(Student **stu, int n){
	*stu = new Student[n+1];
}

void freeStu(Student **stu){
	delete[] (*stu);
}

void inputStu(Student *stu, int n){
	cout<<"Enter "<<n<<" Student Info:"<<endl;
	for(int i = 0; i < n; i++){
		cout<<"Enter No."<<i + 1<<" Student Number(100 ~ 999): ";
		cin>>stu[i].num;
		while(stu[i].num < 100 || stu[i].num > 999){
			cout<<"Number Error! Retry!\nEnter No."<<i + 1<<" Student Number(100 ~ 999): ";
			cin>>stu[i].num;
		}
		
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
		cout<<"Enter No."<<i + 1<<" Student Name: ";
		gets(stu[i].name);

		cout<<"Enter No."<<i + 1<<" Student Score(0 ~100): ";
		cin>>stu[i].score;
		while(stu[i].score < 0 || stu[i].score > 100){
			cout<<"Score Error! Retry!\nEnter No."<<i + 1<<" Student Score(0 ~ 100): ";
			cin>>stu[i].score;
		}

	cout<<endl;
	}
}

void inputStr(char *str, Student *stu, int n){
	ostrstream strout(str, 200);
	for(int i = 0; i < n; i++){
		strout<<stu[i].num<<" "<<stu[i].name<<" "<<stu[i].score<<endl;
	}
	strout<<ends;
}

void outputStr(char *str, Student *stu, int n){
	cout<<"Student Info:"<<endl;
	cout<<str<<endl;
}

int main(){
	Student *stu = NULL;
	char str[200];

	initialStu(&stu, N);
	inputStu(stu, N);
	inputStr(str, stu, N);
	outputStr(str, stu, N);
	freeStu(&stu);

	system("pause");
	return 0;
}

文章来源:https://blog.csdn.net/navicheung/article/details/135352233
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。