首页 > 其他 > 详细

实验六

时间:2019-06-16 12:19:55      阅读:94      评论:0      收藏:0      [点我收藏+]

---恢复内容开始---

第一题:

技术分享图片

在vs2017中使用输入输出流要把文本文件放在cpp文件对应的文件夹内,记事本文件见下一题。

第二题:

    在原代码最后加上

          file.open(newfilename,ios_base::app);

           file<<endl<<"merge successfully.";

在定义处添一句

           ofstream file;

技术分享图片

第三题:

(1)

 

main.cpp

#include <iostream>
#include <string>
#include <cstdlib>
#include "utils.h"
#include<fstream>
#include<ctime>

using namespace std;

int main() {

    string filename,file;

    filename = getCurrentDate();

    cout << filename << endl;

    int n;
    ifstream fin;
    ofstream fout;
    cout << "名单列表文件名:";
    cin >> file;
    cout << "抽取人数";
    cin>>n;
    fin.open(file);
    if (!fin.is_open())
    {
        cerr << "fail to open" << file << endl;
        system("pause");
        exit(0);
    }
    fout.open(filename);
    if (!fout.is_open())
    {
        cerr << "fail to open" << filename << endl;
        system("pause");
        exit(0);
    }
    srand(time(0));
    int line = 0, s;
    string t[100], a;
    while (getline(fin, a))
    {
        t[line++] = a;
    }
    while (n--)
    {
        s = rand() % 83;
        fout << t[s] << endl;
        cout << t[s] << endl;
    }
    fin.close();
    fout.close();
    system("pause");
    return 0;
}

utils,h和utils.cpp已经给出。

技术分享图片

技术分享图片

 

 (2)

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    string file;
    ifstream fin;
    int num = 0, num1 = 0, line = 0;
    cout << "输入要统计的英文文本文件名:";
    cin >> file;
    fin.open(file);
    if (!fin.is_open())
    {
        cout << "fail to open" << endl;
        return 0;
    }
    string n;
    string s[1000];
    int m, i;
    while (getline(fin, n)) {
        s[line] = n;
        line++;//检索每行末尾字符得到行数
        m = n.length();
        for (i = 0; i < m; i++) {
            if (n[i] ==  )
                num1++;//用单词后的空格统计单词数
        }
        num1++;
    }
    for (i = 0; i < line; i++)
    {
        m = s[i].length();
        num += m;//相关函数获取字符数
    }
    fin.close();
    cout << "字符数:" << num << endl;
    cout << "单词数:" << num1 << endl;
    cout << "行数:" << line << endl;
    return 0;
}

 

技术分享图片

 

小结:在vs环境中注意文件的位置,在打开文件后记得要有关闭语句。

实验六

原文:https://www.cnblogs.com/ggwdcs/p/11030950.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!