http://blog.csdn.net/zhangchao3322218/article/details/7930857
#include <iostream>
#include <fstream>
#include < string >
using namespace Std;
void Outputanemptyline ()//Output blank line
{
cout<< "\ n";
}
READ: read by word, between words separated by spaces
void Readdatafromfilewbw ()
{
cout<< "read by word, differentiate between words with spaces" <<endl;
Ifstream fin ("data.txt");
string S;
While (Fin >> s)
{
cout << "Read from File:" << s << endl;
}
}
Read by: Row by line read, the line is read into the character array, line with carriage return to differentiate between lines
void Readdatafromfilelblintochararray ()
{
cout<< "read line by line, read lines into character array, line by carriage return between lines" <<endl;
Ifstream fin ("data.txt");
const int line_length = 100;
Char Str[line_length];
while (Fin.getline (str,line_length))
{
cout << "Read from File:" << str << Endl;
}
}
Read by: Read line by row, read the line into the string, between the lines with carriage return line to differentiate
Compared with the previous method, this method is more flexible, it is recommended to use
void Readdatafromfilelblintostring ()
{
cout<< "read line by line, read lines into string, line by carriage return between lines" <<endl;
Ifstream fin ("data.txt");
string S;
while (Getline (fin,s))
{
cout << "Read from File:" << s << endl;
}
}
Read mode with error detection
void Readdatawitherrchecking ()
{
string filename = "DataFUNNY.txt";
Ifstream Fin (FILENAME.C_STR ());
if (!fin)
{
cout << "Error opening" << filename << "for input" << Endl;
Exit (-1);
}
}
int main ()
{
READDATAFROMFILEWBW (); Read word-by-phrase into a string
Outputanemptyline (); Output blank Line
Readdatafromfilelblintochararray (); Read a word into a character array
Outputanemptyline (); Output blank Line
Readdatafromfilelblintostring (); Read word-by-phrase into a string
Outputanemptyline (); Output blank Line
Readdatawitherrchecking (); Read with detection
return 0;
}
Files in C + + read by line and read by Word backup