实验7 流类库和输入输出

基础练习

(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 << '
';
    cout.unsetf(ios_base::adjustfield); //取消对齐方式的设置
    cout.precision(2);// 设置浮点数输出精度值为2
    cout.setf(ios_base::uppercase|ios_base::scientific); //设置为浮点数的显示参数
    cout << 831.0 ;
    cout.flags(original_flags); //恢复保存的格式化参数设置
    return 0;
}
  • 运行截图:

(2)课本习题11-3

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream file;
    file.open("test1.txt");
    file<<"已成功写入文件!";
    file.close();
    return 0;
}
  • 运行截图

  • 写入文件截图:

(3)课本习题11-4

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
    string n;
    ifstream file;
    file.open("test1.txt");
    getline(file,n);
    cout<<n<<endl;
    file.close();
    return 0;
}
  • 运行截图:

应用练习

(1)

#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
#include<ctime>
const int MAX = 83;
using namespace std;

int main() {
    ifstream file;
    file.open("list.txt");//打开文件
    if (!file) {
        cout << "打开文件失败" << endl;
        return 1;
    }
    string list[MAX];
    string str;
    for(int i=0;i<MAX;i++){
        getline(file, str); 
        list[i]=str;
    }
    file.close();
    ofstream outfile;
    outfile.open("roll.txt");
    srand((unsigned)time(NULL));
    int a;
    for (int i = 0; i<5; i++){
        a = rand() % MAX + 1;
        cout << list[a] << endl;
        outfile << list[a] << endl;
    }
    outfile.close();
    return 0;
}
  • 运行截图

不知道为什么 序号,学号,英文名都可以成功输出,中文名和班级输出都是乱码。

(2)

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
    string name;
    cout << "请输入文件名:" << endl;
    cin >> name;
    ifstream file;
    file.open(name);
    if (!file) {
        cout << "打开错误" << endl;
        return 1;
    }
    long line = 0, word = 0, ch = 0;
    string n;
    unsigned long m;
    while (getline(file,n))
    {
        ++line;
        m=n.size();
        ch+=m;
        for(unsigned long i=0;i<m;i++){
            if((n[i]>='A'&&n[i]<='Z')||(n[i]>='a'&&n[i]<='z')){
                if(n[i+1]<'A'||(n[i+1]>'Z'&&n[i+1]<'a')||n[i+1]>'z')
                    word+=1;
            }
        }
    }
    cout << "字符数:" << ch << endl << "单词数:" << word << endl << "行数:" << line<<endl;
    file.close();
    return 0;
}
  • 运行截图
原文地址:https://www.cnblogs.com/jiahewang/p/9203964.html