/*
用I/O流以文本方式建立一个文件test1.txt,写入字符 “已成功写入文件!”,
用其他字处理程序打开,看看是否正确写入
*/
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream file1("c:\\users\\1\\desktop\\test1.txt", ios_base::out);
file1<<"已成功写入文件!"<<endl;
file1.close();
return 0;
}
/* 使用I/O流以文本方式打开 11-3 建立的文件,读出其内容并显示出来 */ #include<iostream> #include<fstream> using namespace std; int main() { char a[100]; ifstream file("c:\\users\\1\\desktop\\test1.txt"); if(!file) { cout<<"fail to open"; return 1; } file.getline(a,100); cout<<a; file.close(); return 0; }
#include<iostream> #include<fstream> #include<string> using namespace std; int main() { //输出段落 char a[10000]; ifstream file("c:\\users\\1\\desktop\\article.txt"); if(!file) { cout<<"failed to open."; return 1; } while(file.getline(a,10000)) { cout<<a<<endl; } cout<<endl; //字符数 file.clear(); file.seekg(0); int j=0; char c; while(file.get(c)) j++; cout<<"字符数为:"<<j<<endl; //单词数 file.clear(); file.seekg(0); string world; int i=0; while(file>>world) i++; cout<<"单词数为:"<<i<<endl; //行数 file.clear(); file.seekg(0); int line=0; while(file.getline(a,10000)) line++; cout<<"行数为:"<<line<<endl; file.clear(); file.seekg(0); char m; file>>m; int n; while(m=getchar()!=EOF) { if(m=='\n') n++; } cout<<n<<endl; file.close(); return 0; }
11-7电脑无法运行,不知道怎么回事。
班级的那题我先后用结构体和类写的,但是连文本的输出都做不到,我要去看看别人写的代码感悟一下。(死鱼安乐.jpg)