Format text(ifstream, ofstream)

This is a discussion on Format text(ifstream, ofstream) within the C++ Programming forums, part of the General Programming Boards category; Originally Posted by R.Stiltskin Why are you writing the entire buffer? If you read a 5 letter word into a ...

  1. #31
    Registered User
    Join Date
    Feb 2009
    Posts
    72
    Quote Originally Posted by R.Stiltskin View Post
    Why are you writing the entire buffer? If you read a 5 letter word into a 70 character buff, buff contains those 5 letters, plus a '\0', plus 64 bytes of garbage.

    Use
    Code:
    output << buff;
    output.close();
    which will stop writing when it reaches the null character.
    i had tried that too but the output file was blank.

  2. #32
    Registered User
    Join Date
    Feb 2003
    Posts
    595
    Quote Originally Posted by jackfraust View Post
    i had tried that too but the output file was blank.
    That will only happen if there was a 0 at the beginning of buff (unless you have another error someplace else in your code). Take a look at this. Try running it & see what the output is. Whatever "cout << " sends to the screen, "output << " will send exactly the same thing to your file (assuming of course that you have defined output as an ofstream and opened it):
    Code:
    #include <iostream>
    #include <fstream>
    #include <cstring>
    using namespace std;
    
    int main () {
      ifstream input("input.txt");
    //  ofstream output("output.txt");
      const int MAX = 70;  // instead of 100 
      char buff[MAX];
    
        int i;
        for(i = 0; i<5; ++i )
          buff[i] = 98+i;
         
        cout << "I did not terminate my string with a 0 so strlen\n";
        cout << "will give the length from buff[0] to the first 0 it happens\n";
        cout << "to find.\nThis prints every byte from buff[0] up to and\n";
        cout << "including the first \"random\" zero as a 1-byte unsigned number:\n";
        for(i = 0; i <= strlen(buff); ++i )
          cout << (int)(unsigned char)*(buff+i) << "\n";
        cout << endl;
        cout << "Some of the \"garbage\" characters may be unprintable, or line\n";
        cout << "feed or backspace or carriage return or extended ascii chars.\n";
        cout << "Here's the same thing when cout tries to show it as text:\n"; 
        cout << buff << endl;
    
        cout << "Now see what happens if I properly terminate the string.\n";
        buff[5] = '\0';
        cout << "As numbers:\n";
        for(i = 0; i <= strlen(buff); ++i )
          cout << (int)(unsigned char)*(buff+i) << " ";
        cout << endl <<endl;
        cout << "and as letters:\n";
        cout << buff <<endl;
    
    }

  3. #33
    Registered User
    Join Date
    Feb 2003
    Posts
    595
    What I don't understand is why, when I run the code that I posted in #32, cout prints a garbage character at the beginning of the line "Now see what happens if I ...".

    This happens even if I put "cout.flush()" before that line. The only way to avoid that seems to be to print any non-printable ascii char before that line.

    This problem does not occur when I send the output to a file rather than the console.

  4. #34
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    It's probably simply that you've got garbage characters at the end of buff - there is no good way of predicting what they will do or what effect they will have, since it's "random" characters - and they may well mean just about anything including "move down a row" or "move up a row" or anything else that you can't tell what it means.

    [Note, they are not as random as the result of rand(), but they are random in the sense that they are not defined by the program as such - they will have whatever value happens to be in the memory at that location - which if you have the same calling sequence for multiple runs will possibly be similar or even the same].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #35
    Registered User
    Join Date
    Feb 2003
    Posts
    595
    Thanks.

    Quote Originally Posted by matsp View Post
    [Note, they are not as random as the result of rand() ...
    Yes, that's why I called them "random".

    (I suppose I should also call the output of rand() "random", but that's another topic altogether and will only confuse the op even more.)

  6. #36
    Registered User
    Join Date
    Feb 2009
    Posts
    72
    Quote Originally Posted by R.Stiltskin View Post
    That will only happen if there was a 0 at the beginning of buff (unless you have another error someplace else in your code). Take a look at this. Try running it & see what the output is. Whatever "cout << " sends to the screen, "output << " will send exactly the same thing to your file (assuming of course that you have defined output as an ofstream and opened it):
    Code:
    #include <iostream>
    #include <fstream>
    #include <cstring>
    using namespace std;
    
    int main () {
      ifstream input("input.txt");
    //  ofstream output("output.txt");
      const int MAX = 70;  // instead of 100 
      char buff[MAX];
    
        int i;
        for(i = 0; i<5; ++i )
          buff[i] = 98+i;
         
        cout << "I did not terminate my string with a 0 so strlen\n";
        cout << "will give the length from buff[0] to the first 0 it happens\n";
        cout << "to find.\nThis prints every byte from buff[0] up to and\n";
        cout << "including the first \"random\" zero as a 1-byte unsigned number:\n";
        for(i = 0; i <= strlen(buff); ++i )
          cout << (int)(unsigned char)*(buff+i) << "\n";
        cout << endl;
        cout << "Some of the \"garbage\" characters may be unprintable, or line\n";
        cout << "feed or backspace or carriage return or extended ascii chars.\n";
        cout << "Here's the same thing when cout tries to show it as text:\n"; 
        cout << buff << endl;
    
        cout << "Now see what happens if I properly terminate the string.\n";
        buff[5] = '\0';
        cout << "As numbers:\n";
        for(i = 0; i <= strlen(buff); ++i )
          cout << (int)(unsigned char)*(buff+i) << " ";
        cout << endl <<endl;
        cout << "and as letters:\n";
        cout << buff <<endl;
    
    }
    Here's the code:
    Code:
    #include <fstream>
    using std::ofstream;
    using std::ifstream;
    #include <iostream>
    using std::cin;
    using std::cout;
    using std::cerr;
    #include <sstream>
    #include <iomanip>
    #include <cstring>
    using std::string;
    using namespace std;
    #include <cstdlib>
    using std::exit;
    #include <stdio.h>
    #include <iterator>
    
    
    int main (void)
    {
    
    
    	int width;   //width of output line text
    	
    	string name; //input string for location of text file
    	
    	cout << "Enter name of input text file(location on disk):  "<<endl;  
    	getline (cin, name);				//Prompts user to input source text	
    
    	ifstream input;					//create stream object homework
    	input.open ( name.c_str() );		//reads source text file
    	
    	cout << "\n\nEnter name of the output text file:  " <<endl;
    	getline (cin, name); //Promt user to input output text
    
    	ofstream output;	//create stream object homework2
    	output.open (name.c_str() );
    
    	if (!input) {
        cerr << "Unable to open file hw6.txt";
    	exit(1); }  // call system to stop
    
    	if(!output){
    	cerr << "Unable to create text file\n";
    	exit(1);} //call system to stop
    	
    // create reader objects
    
    	cout << "Enter the width for the output of the text (40 -  70):  " ;  //Prompts for range for output text
    	cin >> width;
    	if ( width < 40 || width > 70 )		//set range for output line text
    		cout << "error...width can't be smaller than 40 or larger than 70...Re-Enter range:  ";		//re-prompts if width exceeds range
    	cin >> width;
    
    
    	const int MAX = 100;
    	char buff[MAX];
    	
      int word_length, line_length = 0;   //declare variables for length of word and line respectively
      if( input >> buff ) {
        line_length += strlen( buff );		// set line length
        cout << buff;
        while( input >> buff ) {
          word_length = strlen( buff );		//set word legnth
          line_length += word_length + 1;
          if( line_length > width ) {	
            cout << "\n" << buff;			//prints newline if line length exceeds desired width
            line_length = word_length;
          } else {
            cout << ' ' << buff;
          }
        }
        cout << "\n";
      }
    
    		
    	
            output << buff;			//stores buff into created text file
            
    		output.close();			//close ofstream
    
    
             input.close();
    	
    
    return 0;
    }
    i used name.c_str() because the compiler was having problem when i tried to Prompt for the source file name. And i didn't have to enter two \\ as i would with cin.

  7. #37
    Registered User
    Join Date
    Feb 2003
    Posts
    595
    Quote Originally Posted by jackfraust View Post
    i used name.c_str() because the compiler was having problem when i tried to Prompt for the source file name. And i didn't have to enter two \\ as i would with cin.
    I'm not sure it was the compiler that was having a problem
    but whatever that was, you seem to have worked it out.



    Quote Originally Posted by jackfraust View Post
    Code:
    	
            output << buff;			//stores buff into created text file
            
    		output.close();			//close ofstream
    
    
             input.close();
    	
    
    return 0;
    }
    Your problem is that by the time you get around to writing to the file, the only thing in buff is the LAST word of the input. Read your code again. The only thing that is EVER in buff is a single word -- the most recent word that was extracted from the input. Each time you read in a new word, it overwrites the previous one. To send everything to the file instead of the screen, replace all of the "cout << buff" lines with "output << buff", etc. Or, if you want the output to go to the console AND the file, do both:
    Code:
    cout << buff;
    output << buff;

  8. #38
    Registered User
    Join Date
    Feb 2009
    Posts
    72
    thanks man, I had to use a conditional structure in case the person using the program input a width that was out of range.

    on the cout, output question. shouldnt cout also be usable when dealing with ofstream?

  9. #39
    Registered User
    Join Date
    Feb 2003
    Posts
    595
    Quote Originally Posted by jackfraust View Post
    on the cout, output question. shouldnt cout also be usable when dealing with ofstream?
    I'm not sure exactly what you are asking here. cout is an ostream object that is predefined to write to standard output -- in general the console. It can be redirected to a file using the cstdio function freopen() but if you do that I don't know if there is any way to restore it to the console. Anyway, there's usually no reason to redirect cout. If you want to write to a file, you simply define another ostream (or ofstream) object for that purpose. When you want to write to the file, use that one; when you want to write to the screen, use cout; when you want to write to both places, use both.

  10. #40
    pom
    pom is offline
    Registered User
    Join Date
    Apr 2009
    Posts
    1
    hay i have been having the same problem my compiler is not read it properly
    do you have more methods of doing this "ofstream fileOut(P)" taking user input and using it as a file address....



    here is my program i could not get to work!!!!

    Code:
    int main()
    {
    
    string P = "";
    
    cout << "Input Directery Example: \" C:\\Users\\mugen\\Desktop\\data.txt \" " << endl;
    
    getline(cin, P);
    
    ofstream fileOut(P);  //does not seem to read string "P" how do i get it to work
    
    
    system("pause");
    }

    i don't have to overload "ofstream.open()" do it if so what is the definition for it...i haven't learned more then operation overload yet!!!

  11. #41
    Registered User
    Join Date
    Feb 2003
    Posts
    595
    The ofstream constructor takes a c-string (char array) as its argument, not a std::string.

    Try
    Code:
    ofstream fileOut( P.c_str() );

Page 3 of 3 FirstFirst 123
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. GradeInfo
    By kirksson in forum C Programming
    Replies: 23
    Last Post: 07-16-2008, 03:27 PM
  2. Compression/Decompression Wave File and MP3
    By cindy_16051988 in forum Projects and Job Recruitment
    Replies: 51
    Last Post: 04-29-2006, 06:25 AM
  3. Seeking Format Advice
    By PsychoBrat in forum Game Programming
    Replies: 3
    Last Post: 10-05-2005, 05:41 AM
  4. Capturing key presses
    By cgod in forum Windows Programming
    Replies: 6
    Last Post: 11-25-2004, 12:10 PM
  5. Using ofstream in private of a class-errors
    By loobian in forum C++ Programming
    Replies: 3
    Last Post: 12-13-2003, 09:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21