第七次实验
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); //清除对齐方式 cout.precision(2); cout.setf(ios_base::uppercase|ios_base::scientific); //精度值确定小数点之后的小数位数 cout<<831.0; cout.flags(original_flags); //恢复初始化的格式参数 return 0; }
运行结果

11-3
#include<iostream> #include<fstream> using namespace std; int main() { ofstream a1("text.txt"); a1<<"已成功写入文件!"; //写入字符 a1.close(); return 0; }
运行结果截图


11-4
方法一
#include<iostream> #include<fstream> using namespace std; int main(){ ifstream a2("text.txt"); string m; getline(a2,m); cout<<m; a2.close(); return 0; }
方法二
#include<iostream> #include<fstream> using namespace std; int main(){ char m; ifstream a2("text.txt"); while (a2.get(m)) cout<<m; a2.close(); return 0; }
运行结果截图

第二题
(1)
#include <iostream> #include <stdlib.h> #include <string.h> #include <time.h> #define M 200 #include <fstream> using namespace std; void randStr(FILE *p, char *str); int main(int a, char **g) //指向字符型指针的指针 { int i; FILE *p; char *str = (char *)malloc(M+1); //申请内存 for(i=0;i<=5;i++){ if (str == NULL) //如果指针为空 { return 1; } if ( (p = fopen("list.txt", "r")) == NULL) //打开list文件,文件是空的 { printf("文件打开失败!\n"); } else { randStr(p, str); //随机抽取 printf("%s", str); fclose(p); //关闭文件 free(str); //释放str所占空间 } ofstream a("text.txt"); a<<p; a.close(); return 0; } } void randStr(FILE *p, char *str) { int l=0; srand(time(NULL)); //生成随机数 char b[M]; if (p == NULL) { return ; } while ( (fgets(b, M, p)) != NULL) //从指针p中读取199个字符存到b中,不为空就继续往下执行 { l++; if (rand()%l< 1) { cout<<b; }}}
运行结果

可以生成随机数,但是写入记事本之后就是乱码了,有可能是因为我的系统不兼容的问题,使用实验中给的list文件我在运行之后就打不开,之后我把它复制到自己的记事本上就可以打开了。但是代码本身也存在问题,有几次运行之后显示的数据并不是五个,我尝试着用循环,但是还是不行。
(2)
# include<iostream> #include<stdlib.h> #include<string.h> using namespace std; int main() { long int i, c; FILE *fp;//文件指针 char name[1000],ch=0,str[1000]; int line=0; scanf("%s",name);//自己输入文件名 if((fp=fopen(name,"r"))==NULL) {printf("打开文件失败!\n",name); } else { for (int i=0;i<strlen(str);i++) { if ((ch >='a' && ch <= 'z') || (ch>= 'A' && ch<= 'Z')) ch++; { if (ch==','||ch=='.'||ch=='?'||ch=='!'||ch==' ') c++;}//统计单词个数 line++;} } cout<<"字符串长度:"<<ch<<endl; cout<<"单词数:"<<c<<endl; cout<<"行数:"<<line<<endl; return 0; }
运行结果截图

这题做的不对,但是我对单词和字符串的判断应该没有错误,而且我没用到这章的内容,应该还要有个打开文件的函数,但是我不懂怎么从键盘来输入这个文件名称。
浙公网安备 33010602011771号