Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String input question..? 1

Status
Not open for further replies.

Sidro

MIS
Sep 28, 2002
197
US
Hi,
This is regard to win32 console c++.
I would like to read an input from a text file, process it, then print it back to the screen, in the same format that was in the file originally.

Example, In the text file I have something like this,
----------------------------------
Hi,
My name is joe. Nice to meet you.

Your friend,
joe.
----------------------------------

After reading the text from the input file, into a variable, the spaces and new lines are lost.
How do I preserve this? I hope you folks understand what im asking. Thanks in advance.
 
Code:
ifstream fin("filename.txt");

if(fin.is_open())
{
	fin.seekg(0, ios::end);
	filsize = file.tellg();
	file.seekg(pos, ios::beg);

	if(filesize > 0)
	{
		char *input = new char[128];
		char *fullfile = new char[filesize + 1];
		fullfile[0] = '\0';

		while(fin.peek() != EOF)
		{
			fin.getline(input, 128);
			strcat(fullfile, input);
		}

		return fullfile;
	}
}

Something like that?
 
Hmm, actually that code is a bit off. You'll have to concatinate '\n' after each getline(), plus of course declare filesize as an int. ;)

To write the file, just use ofstream in a similar way as I used the ifstream but with the '<<' operator, just like you would with cout (fout << fullfile;).

Hope that helps.
 
Try this snippet:
Code:
#include <string>
#include <iostream>
#include <fstream>
...
string text, line;
ifstream f("source.txt");

while (getline(f,line)) // until eof or i/o error
  text += line + "\n";
f.close();
// now you have full text with line delimiters...
// process it; '\n' are not standed in the way (?)...
cout << text << endl; // echoe...
...
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top