11——3
#include<fstream>
using namespace std;
int main()
{
?ofstream file;
?file.open("test1.txt",ios_base::binary);
?file<<"已成功添加字符!";
?file.close();
?return 0;?
?}
?
11-4
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
?char ch;
?ifstream myfile;
?myfile.open("test1.txt");
?while(myfile.get(ch))
?cout<<ch;
?myfile.close();
?return 0;
}
?
?
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<<'\n';
?cout.unsetf(ios_base::adjustfield);//清楚setf中對齊方式的設置
?cout.precision(2);//以小數點后保留2位輸出,遵循四舍五入
?cout.setf(ios_base::uppercase|ios_base::scientific);//科學格式顯示 E,更改了浮點數的顯示格式
?cout<<831.0;
?cout.flags(original_flags);//恢復最初保存的格式化設置
?return 0;
}
?
?
2.
#include<iostream>
#include<fstream>
#include<string>
#include<ctime>
#include<cstdlib>
const int M=83;
using namespace std;
struct stu{
?int num;
?string xh, xm,bj;
};
int main()
{
?string bb;
?stu s[M];
?char y;
?while(cin>>bb)
?{
?ifstream is(bb.c_str());
?if(!is)
?{
??cout<<"error"<<endl;
??exit(1);
?}
?? int i=0;
?? int j,a;
?? while(is>>s[i].num>>s[i].xh>>s[i].xm>>s[i].bj)
?? {
?? ?i++;
?? }
?????
???? ofstream os("text2.txt");
?? srand(time(NULL));
?? cout<<"抽取學生?"<<endl;
?? while(cin>>y&&y=='Y')
?? {
?? ?a=rand()%i+1;
?? ?cout<<s[a].num<<" "<<s[a].xh<<" "<<s[a].xm<<" "<<s[a].bj<<" "<<endl;
?? ?os<<s[a].num<<" "<<s[a].xh<<" "<<s[a].xm<<" "<<s[a].bj<<" "<<endl;
?? ?
??? } ?
?
?is.close();
?os.close();}
?return 0;
}
?
?
?3.
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
? {
??? string bb;
??? cin >> bb;
??? ifstream is(bb.c_str());
???? if (!is) {
???????? cout << "error" << endl;
???????? exit(1);
???? }
???? int li = 1, wo = 0, ch = 0;
???? char c;
???? while (is.get(c))
???? {
???????????? ch++;
???????????? if ((c < 'A' || c > 'Z'&&c < 'a' || c > 'z')&&c!='\n')
???????????????? ++wo;
???????????? if (c == '\n')
???????????????? ++li;
???? }
???? char a;
???? cout<<"查看字符數:a"<<endl<<"查看單詞數:b"<<endl<<"查看行數:c"<<endl;
? while(cin>>a)
? {
? ?switch(a){
? ??case 'a':
? ???cout << "字符數:" << ch << endl;
? ???continue;
? ??case 'b':
?????? cout << "單詞數:" << wo << endl;
????continue;
???case 'c':
?????? cout << "行數:" << li<<endl;
????continue;??
?? }
?? }
???? is.close();
???? return 0;
?}
?
第二道題中當使用getline()輸入文件時,輸出的為亂碼,后考慮用類或者結構體定義每個學生信息,但在輸出時有時會只輸出一個數字。流的掌握不好,有的概念還理解不清。