-
File I/o
Hello, I don't know if its my fault or the author's who wrote the tutorial from where I copied this code, but I can't understand why it prints only "This" instead of the whole text in the txt file ?
Code:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char str[10];
//Creates an instance of ofstream, and opens example.txt
ofstream a_file ( "example.txt" );
// Outputs to example.txt through a_file
a_file<<"This text will now be inside of example.txt";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstream b_file ( "example.txt" );
//Reads one string from the file
b_file>> str;
//Should output 'this'
cout<< str <<"\n";
cin.get(); // wait for a keypress
// b_file is closed implicitly here
}
Thank you
-
The >> operator is reading into the array str[]. I believe it's working as designed. Perhaps you want to read a line at a time, instead of reading a "string" at a time.
Todd
-
What do I do to get "This text will now be inside of example.txt" printed ?
-
Well, first off, since you are using C++, I would suggest using a string instead of a char array. Strings can grow dynamically and you don't have to jack with storage limits.
Then, you can read a line at a time, or, read a "word" at a time in a loop until EOF is hit.
Todd
-
I incresed the size if str to str[50]
Please tell me where I am going wrong:
I think this
should put everything inside "example.txt" into str (I mean the whole sentence)
and this
should display it on the screen ?
-
-
But this
Code:
cout<<"Hello World";
dosen't stop at whitespace ? Maybe I should start all over again :(
-
-
ok so the problem was with and not with cout. b_file ignores everything after whitespace. Thanks.
-
I replaced it with
Code:
b_file.getline(str,49)
and its working.
-
If you use std::string which is found in <string> then you can do...
Code:
std::getline(b_file,str);
That code will get the text (or binary) from file until '\n' is found. This is of course preference, but I personally find it quite helpful when you know for sure than there will be no errors in the file. Also note, that there can be your own terminating character which is the third argument.
Code:
std::getline(b_file,str);
//would be the same as
std::getline(b_file,str,'\n');