+ 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;

22nd Nov 2017, 8:27 PM
Hassan Sajjad
Hassan Sajjad - avatar
8 Antworten
+ 7
you are using C way of doing, which is incorrect in C++ Change : !file With : !file.is_open()
22nd Nov 2017, 8:41 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 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();
22nd Nov 2017, 9:04 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 3
You read from a file when it was opened in write only
22nd Nov 2017, 9:35 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 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
23rd Nov 2017, 7:17 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
22nd Nov 2017, 9:35 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
it is still outputting garbage
22nd Nov 2017, 8:59 PM
Hassan Sajjad
Hassan Sajjad - avatar
+ 1
even if I use string b instead of int b still error occurs
22nd Nov 2017, 9:13 PM
Hassan Sajjad
Hassan Sajjad - avatar
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???
22nd Nov 2017, 9:49 PM
Hassan Sajjad
Hassan Sajjad - avatar