finished

上一篇 / 下一篇  2014-08-05 17:59:32 / 个人分类:mark

// tick.cpp : Defines the entry point for the console application.
// 随机函数;
// 随机从姓、名中分别选择一个字组成学生姓名,随机产生45~100的整数当做学生成绩;
#include "stdafx.h"
#include <ctime>
#include "iostream"
#include "string.h"
#include<iomanip>
#include<fstream>
#define N 10
using namespace std;

struct NameBank
{
 char firstName[20];
 char lastName[10];
}bank[8];
struct Student
{
 char name[20];
 int score;
}stu[N];
int *Random(int X,int Y,const int cct)  //产生一个X~Y的随机数  ;
{
 srand((unsigned)time(NULL)); /*随机种子srand((unsigned)time(0));  */
 int *n = (int *)malloc(cct*sizeof(int));
 for(int i=0;i<cct;i++)
 {
  *(n+i)=rand()%(Y-X+1)+X; /*n为X~Y之间的随机数;*/
 }
 return n;
}
void getName(int idx)  // 随机组合一个名字;
{
 int *n=Random(0,7,20);
 for(int i=0;i<idx;i++)
 {
  int a=n[i],b=n[i+1];
  char fn[20];
  strcpy(fn, bank[a].firstName);
  char ln[10];
  strcpy(ln, bank[a].lastName);
  strcat(fn,ln);
  strcpy(stu[i].name,fn);
 }
 free(n);
}
void readFile() //读文件并赋值;
{
 ifstream myFile("E:\\study\\class\\struct\\random\\name.txt",ios_base::in);
 char line[1000];
 int idx=0;
 while(myFile.getline(line,1000))
 {
  char first[8][10];
  sscanf(line,"%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s",first[0],first[1],first[2],first[3],first[4],first[5],first[6],first[7]);
  if(idx==0)
  {
   for(int i=0;i<8;i++)
   {
    strcpy(bank[i].firstName,first[i]);
   }
  }
  else
  {
   for(int j=0;j<8;j++)
   {
    strcpy(bank[j].lastName,first[j]);
   }
  }
  idx++;
 }
}
void writeFile()  //写入文件并打印;
{
 ofstream myFile("E:\\study\\class\\struct\\random\\student.txt",ios_base::out);
 int *num=Random(45,100,N);
 for(int i=0;i<N;i++)
 {
  
   stu[i].score=num[i];
  myFile<<stu[i].name<<"\t"<<stu[i].score<<endl;
  cout<<stu[i].name<<"\t"<<stu[i].score<<endl;
 }
 free(num);
 myFile.close();
}
int _tmain(int argc, _TCHAR* argv[])
{
 readFile();
 getName(N);
 writeFile();
 return 0;
}

TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-05-01  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 3271
  • 日志数: 3
  • 文件数: 4
  • 建立时间: 2012-05-01
  • 更新时间: 2014-09-01

RSS订阅

Open Toolbar