I'm currently learning writing to and reading from a file in C++, and I stumbled across something I'm not sure I understand.
I'm writing 5 different integers to "ages.txt" file and then I'm using a read_file()
function to read the content of that file and output it to a console. What I don't really understand is that when writing to a file I'm using int
type, and reading back from it I'm using string
type, and numbers are still being read correctly from the "ages.txt" file.
Does that mean there is some conversion happening in the backgroud?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void read_file()
{
ifstream file ("ages.txt");
vector<string> read_age;
string input;
while(file >> input)
{
read_age.push_back(input);
}
for(string age : read_age)
{
cout << age << endl;
}
}
int main()
{
ofstream file ("ages.txt");
if(file.is_open())
{
cout << "File was opened" << endl;
}
vector<int> ages;
ages.push_back(12);
ages.push_back(13);
ages.push_back(14);
ages.push_back(15);
ages.push_back(16);
for(int age : ages)
{
file << age << endl;
}
read_file();
return 0;
}
I tried changing string to char type everywhere in the read_file()
function and then output of my console was as follows (with the data that's already in "ages.txt" file):
File was opened
1
2
1
3
1
4
1
5
1
6
Yes, it does mean some conversion is happening.
Using <<
converts whatever you are writing to text. Text is typeless, a sequence of digits could be an integer or it could be a string. Similarly >>
converts whatever text you are reading to some type. Now there is a potential problem here in that some text cannot be converted to some types, but anything can be read as a string.