I want to add a whole text file into my program. I have tried strings but I want to keep the spaces but strings take the spaces as terminating characters. so how do I input an entire file into my program.
Printable View
I want to add a whole text file into my program. I have tried strings but I want to keep the spaces but strings take the spaces as terminating characters. so how do I input an entire file into my program.
One way is to read each line with getline and put the newlines back in.
Code:std::string line, whole_file;
while (std::getline(fin, line)) {
whole_file += line;
whole_line += '\n';
}
Dear,
This program will took an input file "test" from the disk.This txt file should be in the same directory of C++ files.
Code:Have a look at this program,
#include <iostream.h>
#include <fstream.h>
void main()
{
const int max=80;
char buffer[max];
ifstream infile;
infile.open("test.txt");
while(infile)
{
infile.getline(buffer,max);
cout<<buffer<<endl
}
}
I method could be to use the getline( ) function, and place an entire line of text into a <string> object...
Code:#include<string>
#include<fstream>
...
...
...
ifstream infile;
string line_of_text;
string entire_document;
infile.open("c:\\myfile");
while(getline(infile, line_of_text))
{
entire_document += line_of_text;
entire_document += '\n';
}
...
...
*Anon beat me to this post. It's basically the same idea.
Thank You so much works great!
Another choice:Code:#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::ifstream fin(__FILE__); // Insert your filename instead of __FILE__ here.
std::ostringstream oss;
oss << fin.rdbuf();
std::string fileContents = oss.str();
// use fileContents
}
So that's how you do that. I've been trying all sorts of std::getline(delim = some_EOF) for any two streams. It's the buffers... thank you, Daved.