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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Store contents of file into variable

Status
Not open for further replies.

chgifts

Programmer
Jan 21, 2004
1
US
Hello, I am new to c++ and honestly never use it, but I need to write a little script that takes that contents of a file and stores it into a variable.

With that variable(string) I need to create 2 more variables with a substring command. Then I need to write those 2 variabless to the lpt1 printer port.

I currently have this

#include <stdio.h>

void main(void)
{
FILE *fp;
char ch;

fp = fopen(&quot;test.txt&quot;,&quot;r&quot;);
ch = getc(fp);
while(ch!=EOF)
{
putchar(ch);
ch = getc(fp);
}
}

but not sure how to get a substring out of the variable.
I am trying to get out characters 16-24 and 34-52 out of the variable and store them into 2 speperate variable and then write those 2 variable to the lpt1 printer port. I hope this makes sense.
 
OK, here is some C++ code that read an input file, stores it inside a string object and extract 2 substrings :

Code:
#include <iostream>
#include <string>
#include <fstream>
#include <assert.h>
using namespace std;

int main (int argc, char** argv)
{
  if (argc == 2)
    {
      ifstream in (argv[1]);
      assert (in.is_open ());//in_file_open

      in >> noskipws;//do_not_skip_white_space_while_reading_stream      
      string buffer;//store_contents_of_input_file

      while (!in.eof ())
	{
	  char read_char;
	  in >> read_char;
	  buffer += read_char;
	}

      assert (buffer.size () > 24);//correct_size_before_sub_extraction
      string sub1 = buffer.substr (16, 24 - 16);
      assert (buffer.size () > 52);//correct_size_before_sub_extraction
      string sub2 = buffer.substr (34, 52 - 34);

      cout << &quot;sub1 : &quot; << sub1 << endl;
      cout << &quot;sub2 : &quot; << sub2 << endl;
    }

}

This code reads white space chars(\n, etc.) too, if you want to do not, replace :
Code:
in >> noskipws;

by

in >> skipws
Or maybe simply remove this line.


--
Globos
 
Oups, sorrry, I forgot the main's body last line :
Code:
return 0;

--
Globos
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top