---恢复内容开始---
第一题:
在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