实验报告(七)

# include<iostream>
using namespace std;
int main(){
	ios_base::fmtflags original_flags=cout.flags();//1 保存现在的格式化参数设置,以便将来恢复这些设置; 
	cout<<812<<'|';
	cout.setf(ios_base::left,ios_base::adjustfield);//2 把对齐方式由缺省的右对齐改为左对齐; 
	cout.width(10);//3 控制输出宽度为10 
	cout<<813<<815<<'\n';
	cout.unsetf(ios_base::adjustfield);//4 清除对齐方式的设置;
	cout.precision(2);//在输出的时候设定输出值以新的浮点数精度值显示,即小数点后保留( )位 
	cout.setf(ios_base::uppercase|ios_base::scientific);//5 更改浮点数的显示设置; fix是只改小数点后位数,scientific会按照科学计数法改 
	cout<<813.0;
	cout.flags(original_flags);//6 恢复原来的格式化参数设置。
	return 0;
}

// 结果
//812|813 815
//8.13E+002

参考网址:
https://blog.csdn.net/w_linux/article/details/72793651

#include <iostream>
#include <fstream>
using namespace std;
int main (){
	ofstream file;
	file.open("test1.txt");
	file<<"已成功写入文件"; 
	file.close();
	
}

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

开始不知道怎么做,查了一下,有输入和输出两种方式打开文件夹,而这种并不是相对于文件夹而言的,而是相对于我们平时的输出屏幕和输入屏幕。以输入方式打开文件夹是指把文件夹的内容导入程序(然后可以输出于屏幕),反之把内容写进文件夹,就是出了。
参考网址:
https://blog.csdn.net/luo809976897/article/details/51442070

# include <fstream>
# include <iostream>
# include <string>
# include <time.h>
# include <cstdlib>
using namespace std;
int main(){

    string list[83];
    int i=0;
    string str;
	ifstream file("C:\\Users\\奚格\\Desktop\\实验7\\实验7\\list.txt");//输入方式打开文件夹 
	if (!file) {
         cout << "ERROR" << endl;
         return 1;
    }
	while(getline(file,str)){    //参考了同学的 
		list[i]=str;
		i++;	
	}
	ofstream outfile("C:\\Users\\奚格\\Desktop\\实验7\\实验7\\outlist.txt");
	int x;
	srand(time(NULL));
	for(int j=0;j<5;j++){
	     x=rand()%83;
		 cout<<list[x]<<endl;
		 outfile<<list[x]<<endl;	
	}
	file.close();
	outfile.close();
	return 0;
}

借鉴了同学的,学会了getline整行读取并且存入。
一开始自己的输出是空白的一块,后来也是看了同学的,添加了判断,发现自己文件读取失败才导致了空白。
但是自己的运行结果是乱码,很奇怪,复制了同学的试了一下,也是乱码,可能是自己Dev的问题。

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
    string name;
    cout<<"文件名";
    cin>>name;
    ifstream file(name);
    if (!file) {
        cout << "ERROR" << endl;
        return 1;
    }
    long c=0,word=0,line=1;
    char ch;
    file<<ch;
    while (file.get(ch))
    {
            c++;
            if ((ch<'A'||ch>'Z'&&c<'a'||ch>'z')&&c!='\n')
                ++word;
            if (ch=='\n')
                ++line;
    }
    cout<<"字符数:"<<c<<endl;
	cout<<"单词数:"<<word<<endl;
	cout<<"行数:  "<<line<<endl;
    file.close();
    return 0;
}

第三题输入文件名不会,看了同学的,但是我这儿一直报错,就很神奇。

posted @ 2018-06-20 23:57  花逢君  阅读(131)  评论(0编辑  收藏  举报