1. Read all strings separated by spaces in the specified file.
# Include <fstream>
Ifstream indata; // For the file
Indata. Clear ();
String filename;
Filename = "primes.txt ";
Indata. Open (filename. c_str ());
String temp_word;
// You can also directly read the integer data int temp_word here;
// Indata> temp_word;
While (indata. EOF ())
// If the file contains a line break, you need to use while (indata. Good () to determine whether it is at the end of the file.
{
Indata> temp_word;
}
Note: If you use # include <fstream>, you cannot use ifstream,
You can try:
# Include "stdafx. H"
# Include <cstdlib>
# Include <iostream>
# Include <fstream>
# Include <string>
Using namespace STD;
2. Read all characters in the specified file, including Spaces
# Include <fstream>
Ifstream indata;
String filename;
String temp_word;
Filename = "aaa.txt ";
Indata. Open (filename. c_str ());
Indata. seekg (0, IOS: End );
Streampos PS = indata. tellg ();
// Cout <"file size:" <ps <Endl;
Indata. Close ();
Const char * filenamechar = filename. c_str ();
Ifstream myinf (filenamechar );
Int size = Ps;
// Char STR [1000000]; //
Char * STR = new char [size + 100];
// Read File
Myinf. Read (STR, PS );
Myinf. Close (); // close file
For (INT I = 0; I <ps; I ++)
{
// Test what has been read
// Cout <STR [I];
// Store character
If (STR [I]! =-52) // if not null
{
Temp_word = STR [I];
}
}
3. Write the specified content to the file
Format and write
# Include <iostream>
Using namespace STD;
# Include <string>
# Include <fstream>
// # Include <cstdlib>
# Include <iomanip>
Ofstream F1;
String fileout = "tabular.txt ";
F1.open (fileout. c_str ());
If (! F1) return;
F1 <setiosflags (IOs: right );
F1 <SETW (15) <"employee ID number ";
F1 <SETW (20) <"name ";
F1 <SETW (15) <"gross pay ";
F1 <SETW (15) <"tax ";
F1 <SETW (15) <"net pay" <Endl;
F1.close ();
F1 <SETW (15) <setprecision (2) <grosspay;
You can use setprecision to set the reserved digits of a floating point.
Unformatted write
// String nowdata = "employee ID number name gross pay tax net pay ";
/*
Int size = nowdata. Size ();
Char * Ch = new char [1];
* Ch = * (nowdata. c_str ());
// Char * buffer;
For (INT I = 0; I <size; I ++)
{
* Ch = * (nowdata. substr (I, 1). c_str ());
// Char * buffer;
F1.write (CH, 1 );
}
*/
F1.close ();