File IO of Numeric and String Data
Understand the file handling of Numeric and String data in C++.
We'll cover the following...
Challenge
Write a program to write numeric and string data into a file called SAMPLE.TXT
. Read the same file back and display the contents read on the screen.
Sample run
root@educative:/usr/local/educative# g++ main.cpp
root@educative:/usr/local/educative# ./a.out
Z
25
473.14
Hyperbole!
root@educative:/usr/local/educative# cat SAMPLE.TXT
Z
25
473.14
Hyperbole!
Coding exercise
Your job is to write the code for writing and reading to the file in the main( )
function.
// File IO of numeric and string data #include <fstream> #include <iostream> int main( ) { char ch = 'Z' ; int i = 25 ; float a = 473.14f ; char str[ ] = "Hyperbole!" ; // Your code goes here // send data to screen std :: cout << ch << std :: endl ; std :: cout << i << std :: endl ; std :: cout << a << std :: endl ; std :: cout << str << std :: endl ; return 0 ; }
Coding solution
The following code widget has the solution for the challenge explained above.
// File IO of numeric and string data #include <fstream> #include <iostream> int main( ) { char ch = 'Z' ; int i = 25 ; float a = 473.14f ; char str[ ] = "Hyperbole!" ; // create file for output std :: ofstream outfile ( "SAMPLE.TXT" ) ; // send data to file outfile << ch << std :: endl ; outfile << i << std :: endl ; outfile << a << std :: endl ; outfile << str << std :: endl ; outfile.close( ) ; std :: ifstream infile ( "SAMPLE.TXT" ) ; // read data from file infile >> ch >> i >> a >> str ; // send data to screen std :: cout << ch << std :: endl ; std :: cout << i << std :: endl ; std :: cout << a << std :: endl ; std :: cout << str << std :: endl ; return 0 ; }
Explanation
The contents of the file are displayed on the console using the cat
command followed by the filename, like this:
cat SAMPLE.TXT
To begin with, we have defined an object called outfile
, of type ofstream
...