实验7 流类库和输入输出

基础练习

(1)课本习题11-7

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

(2)课本习题11-3

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

  • 写入文件截图:
    实验7 流类库和输入输出_第1张图片

(3)课本习题11-4

#include 
#include 
#include 
using namespace std;
int main() {
    string n;
    ifstream file;
    file.open("test1.txt");
    getline(file,n);
    cout<
  • 运行截图:

应用练习

(1)

#include
#include
#include
#include
#include
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
  • 运行截图
    实验7 流类库和输入输出_第2张图片

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

(2)

#include
#include
#include
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='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<
  • 运行截图
    实验7 流类库和输入输出_第3张图片

你可能感兴趣的:(实验7 流类库和输入输出)