+ 1
Why is printing garbage?
fstream file; file.open("hassan.txt",ios::out); if (!file) { cout << "file not opened succesfully" << endl; } int b=98; file << b; string a; file >> a; cout << a; return 0;
8 Antworten
+ 7
you are using C way of doing, which is incorrect in C++
Change :
!file
With :
!file.is_open()
+ 3
seems logical, you entered an int, then read a string. If you want to cast the int to string, either use atoi function (C method, optimized but not generic) or use ostringstream like that :
#include <sstream>
#include <string>
...
osstringstream oss;
int a = 100;
std::string s;
oss << a;
s = oss.str();
+ 3
You read from a file when it was opened in write only
+ 3
No, in sololearn it is because the file do not exist
On your visual studio, it is because you need to add :
file.seekg(0,ios::beg);
Between writing and reading
+ 1
it is still outputting garbage
+ 1
even if I use string b instead of int b still error occurs
0
yes it is ok
if I open it just once and use the flags like
ios::in|ios::out error occurs
(in sololearn file is not opening in visual studio file opens but there is output problem)
it means that we should not use ios:: out while oopening if we r reading from file???