#include <iostream>
#include <fstream>
#include <string>
using namespace Std;
Output blank Line
void Outputanemptyline ()
{
cout << "\ n";
}
READ: read by word, between words separated by spaces
Read data from the file, Word by word
When used in this manner, we'll get space-delimited bits of text from the file
But all of the whitespace, separated words (including newlines) was lost.
void Readdatafromfilewbw ()
{
Ifstream fin ("c:\\users\\byte\\desktop\\huang.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
If we were interested in preserving whitespace,
We could read the file in Line-by-line using the I/O getline () function.
void Readdatafromfilelblintochararray ()
{
Ifstream fin ("c:\\users\\byte\\desktop\\huang.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
If you want to avoid reading into character arrays,
You can use the C + + string Getline () function to read lines into strings
void Readdatafromfilelblintostring ()
{
Ifstream fin ("c:\\users\\byte\\desktop\\huang.txt");
string S;
while (Getline (Fin, s))
{
cout << "Read from File:" << s << endl;
}
}
Read mode with error detection
Simply evaluating an I/O object in a Boolean context would return false
If any errors has occurred
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
GetChar ();
return 0;
}
C + + reads data from TXT, data is not a line path (practical)