+ 1
How is c_str() function working in this C++ code?? Please explain(complete code in Description)
Int main { fstream file; string word,filename; filename="1.txt"; file.open(filename.c_str()); while(file>>word) cout<<word; } I wanna know how is this code displaying the Text file's content word by word?? I mean what is c_str() doing here & how is while loop jumping to next word after reading first one?
3 Answers
+ 6
std::fstream::open () expects file path as a C style string ( const char * ), but the name you have got ("filename") is of type std::string.
Here, c_str () is used to perform the conversion ( from std::string to const char * )
---
Usefull links :
- open () : https://www.cplusplus.com/reference/fstream/fstream/open/
- c_str () : https://en.cppreference.com/w/cpp/string/basic_string/c_str
+ 2
Arsenic thanks alot bruh! But how is the while(file>>word) working??
I mean the string was "We are happy"
So this code print "We" then "are" then "happy". Shouldn't it print "We" over and over again
Bcuz there's nothing specifying it to jump to the next word after it prints "We". So how does it jump "are" next time & then "happy"???
+ 1
G'day Farzam Baig did you find out about extraction operators? I didn't know much so I found them on the same site that Arsenic linked.
https://www.cplusplus.com/reference/istream/istream/operator%3E%3E/