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.
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'; }
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
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.
Last edited by The Brain; 06-24-2007 at 10:13 AM. Reason: give credit to the fast poster
- "Problem Solving C++, The Object of Programming" -Walter Savitch
- "Data Structures and Other Objects using C++" -Walter Savitch
- "Assembly Language for Intel-Based Computers" -Kip Irvine
- "Programming Windows, 5th edition" -Charles Petzold
- "Visual C++ MFC Programming by Example" -John E. Swanke
- "Network Programming Windows" -Jones/Ohlund
- "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
- "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel
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.
"If you tell the truth, you don't have to remember anything"
-Mark Twain