C++入门 I/O 文件读入 流读入
1.文件读入
1)包含头文件 fstream文件读写
其它:iostream控制台读写,sstream string读写
2)定义文件流读入对象
<i>注意绑定文件时,函数参数是C风格字符数组,而不是string对象
处理方法 定义string对象s 然后用s.c_str获取C风格字符串
<ii>检查文件是否打开成功
(exception思想)
<iii>cerr 迅速输出错误信息
示例程序
#include<iostream>//控制台读写 #include<fstream>//文件读写 #include<string> using namespace std; int main(int argc, char** arg) { string fileName = "data.txt";//文件名保存在string中 ifstream infile(fileName.c_str());//定义文件读入流对象,并绑定文件 if (!infile) { cerr << "erro: unable to open input file: " << fileName<< endl; } string s; while (getline(infile, s)) s += s; cout << s; system("pause"); return 0; }
2.流读入
1)从文件中读取整行数据到line中 方法如1中所讲
2)创建stringstream对象 istream,利用istream>>读入line中的单词
file内容:apple milk
#include<iostream>//控制台读写 #include<fstream>//文件读写 #include<string> #include<sstream> using namespace std; int main(int argc, char** arg) { string fileName = "data.txt";//文件名保存在string中 ifstream infile(fileName.c_str());//定义文件读入流对象,并绑定文件 if (!infile) { cerr << "erro: unable to open input file: " << fileName<< endl; } string line, word1,word2; while (getline(infile, line)) { istringstream istream(line); istream >> word1>>word2; } cout << "word1 is: " << word1 << " word2 is: " << word2; system("pause"); return 0; }
作品原创 转载请注明出处