码迷,mamicode.com
首页 > 编程语言 > 详细

C++实验七

时间:2018-06-21 00:02:30      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:查看   nal   小数点   struct   cti   cas   names   switch   定义   

11——3

#include<fstream>
using namespace std;
int main()
{
 ofstream file;
 file.open("test1.txt",ios_base::binary);
 file<<"已成功添加字符!";
 file.close();
 return 0; 
 }

 

技术分享图片

11-4

#include<fstream>
#include<iostream>
using namespace std;
int main()
{
 char ch;
 ifstream myfile;
 myfile.open("test1.txt");
 while(myfile.get(ch))
 cout<<ch;
 myfile.close();
 return 0;
}技术分享图片

 

技术分享图片

 

11-7

#include<iostream>
using namespace std;
int main()
{
 ios_base::fmtflags original_flags=cout.flags();//保存现在格式化设置,方便以后的恢复使用
 cout<<812<<‘|‘;
 cout.setf(ios_base::left, ios_base::adjustfield);//输出格式改为右对齐
 cout.width(10);//输出域宽设为10
 cout<<813<<815<<‘\n‘;
 cout.unsetf(ios_base::adjustfield);//清楚setf中对齐方式的设置
 cout.precision(2);//以小数点后保留2位输出,遵循四舍五入
 cout.setf(ios_base::uppercase|ios_base::scientific);//科学格式显示 E,更改了浮点数的显示格式
 cout<<831.0;
 cout.flags(original_flags);//恢复最初保存的格式化设置
 return 0;
}

 

技术分享图片

 

2.

#include<iostream>
#include<fstream>
#include<string>
#include<ctime>
#include<cstdlib>
const int M=83;
using namespace std;
struct stu{
 int num;
 string xh, xm,bj;
};
int main()
{
 string bb;
 stu s[M];
 char y;
 while(cin>>bb)
 {
 ifstream is(bb.c_str());
 if(!is)
 {
  cout<<"error"<<endl;
  exit(1);
 }
   int i=0;
   int j,a;
   while(is>>s[i].num>>s[i].xh>>s[i].xm>>s[i].bj)
   {
    i++;
   }
     
     ofstream os("text2.txt");
   srand(time(NULL));
   cout<<"抽取学生?"<<endl;
   while(cin>>y&&y==‘Y‘)
   {
    a=rand()%i+1;
    cout<<s[a].num<<" "<<s[a].xh<<" "<<s[a].xm<<" "<<s[a].bj<<" "<<endl;
    os<<s[a].num<<" "<<s[a].xh<<" "<<s[a].xm<<" "<<s[a].bj<<" "<<endl;
    
    }  
 
 is.close();
 os.close();}
 return 0;
}

 

技术分享图片

 

 3.

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
  {
    string bb;
    cin >> bb;
    ifstream is(bb.c_str());
     if (!is) {
         cout << "error" << endl;
         exit(1);
     }
     int li = 1, wo = 0, ch = 0;
     char c;
     while (is.get(c))
     {
             ch++;
             if ((c < ‘A‘ || c > ‘Z‘&&c < ‘a‘ || c > ‘z‘)&&c!=‘\n‘)
                 ++wo;
             if (c == ‘\n‘)
                 ++li;
     }
     char a;
     cout<<"查看字符数:a"<<endl<<"查看单词数:b"<<endl<<"查看行数:c"<<endl;
  while(cin>>a)
  {
   switch(a){
    case ‘a‘:
     cout << "字符数:" << ch << endl;
     continue;
    case ‘b‘:
       cout << "单词数:" << wo << endl;
    continue;
   case ‘c‘:
       cout << "行数:" << li<<endl;
    continue;  
   }
   }
     is.close();
     return 0;
 }

技术分享图片

 

第二道题中当使用getline()输入文件时,输出的为乱码,后考虑用类或者结构体定义每个学生信息,但在输出时有时会只输出一个数字。流的掌握不好,有的概念还理解不清。

C++实验七

标签:查看   nal   小数点   struct   cti   cas   names   switch   定义   

原文地址:https://www.cnblogs.com/devin-booker/p/9206529.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!