第7次C++实验

一。实验结论:

1.基础部分:

(1)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);//清除对齐方式
    cout.precision(2);//确定输出数值精确度为小数点后两位
    cout.setf(ios_base::uppercase|ios_base::scientific);//转换到科学计数法模式
    cout<<831.0;
    cout.flags(original_flags);//转换回标准输出模式;
    return 0;
}

(2)11-3

代码:

#include<fstream>
using namespace std;
int main()
{
    ofstream file1("test1.txt");
    file1<<"The file has been written successfully";
    file1.close();
    return 0;
}

结论:

(3)11-4

代码:

#include<fstream>
#include<iostream>
using namespace std;
int main()
{
    char ch;
    ifstream file2("test1.txt");
    while(file2.get(ch))
    {
        cout<<ch;
    }
    file2.close();
    return 0;
}

结论:

2.应用部分

(1)代码

#include<iostream>
#include<cstdlib>
#include<string>
#include<fstream>
using namespace std;
struct student
{
    string num;
    string snum;
    string name;
    string cla;
}a[200];
using namespace std;
int main()
{
    int i,j,n=0;
    ifstream fin("list.txt");
    while(fin>>a[n].num>>a[n].snum>>a[n].name>>a[n].cla)
    {
        n++;
    }
    fin.close();
    ofstream fout("roll.txt");
    for(i=0;i<5;i++)
    {
        j=rand()%n+1;
        cout<<a[j].num<<" "<<a[j].snum<<" "<<a[j].name<<" "<<a[j].cla<<endl;
        fout<<a[j].num<<" "<<a[j].snum<<" "<<a[j].name<<" "<<a[j].cla<<endl;
    }
    fout.close();
    return 0;
}

报错:

注:这个问题我研究了将近2天,也借鉴了别的同学的程序,还是没有找到好的解决办法,恳请大佬们的帮助。。。。

(2)代码(借鉴了大佬的思路)

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    ifstream in("article.txt");
    int line=0,word=0,num=0;
    string s;
    int i,m;
    while(getline(in,s))
    {
        line++;
        m=s.size();
        num=num+m;
        for(i=0;i<m;i++)
        {
            if((s[i]>='A'&&s[i]<='Z')||(s[i]>='a'&&s[i]<='z'))
            {
                if((s[i+1]<='A'||s[i+1]>='Z')&&(s[i+1]<='a'||s[i+1]>='z'))
                {
                    word=word+1;
                }
            }
        }
    }
    cout<<"The article has "<<line<<" lines, "<<word<<" words, "<<num<<" letters.";
    return 0;
}

思路:逐行读取,根据读取次数计算行数,再逐行统计出字符数与单词数(在每个单词最后一个字母的地方统计单词数+1),计算出每行字符数的总和与单词数的总和。

结果:

 

二。实验分析与讨论:

    从我个人角度而言,本次实验是本学期难度最大的实验,基础部分做得还算比较顺畅,到了应用部分就卡得不行了。。。。应用部分的两道题我都或多或少地借鉴了一下别的同学的思路与方法,但是我都通过做类似题的方式确保我可以把借鉴同学的思路与方法的吃透,我觉得这种学习方法效率还不错、、、、、

猜你喜欢

转载自www.cnblogs.com/manganese123/p/9203181.html