Thread: Getline and strings...

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    11

    Getline and strings...

    I am trying to parse a code textfile using getline but it always discards the newline character and inserts a null, I want to know if their is an easy way to append a newline to the end of the string overwriting the null character when writing the outputfile. If I use getline in and I try to output myfile << line; it just creates line of text when you open it in a text editor because their is no newlines.

    Originally in the examples I was reading from, I was reading and writing text files character by character and the files would copy exactly, but using string functions on files means the formatting of the file gets lost.

    I'm not sure if I'm using the right class to be doing text parsing but basically I just want to parse the file so I can change the numerical values in text mode and then re-output the file.

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    You just need to re-add the newline to output. All the I/O functions are set to read up until that character is reached.

    So after you process your string, just append the newline to the output.
    Woop?

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    11
    Sec I may have found the prob.

  4. #4
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by sting777 View Post
    I am trying to parse a code textfile using getline but it always discards the newline character and inserts a null, I want to know if their is an easy way to append a newline to the end of the string overwriting the null character when writing the outputfile. If I use getline in and I try to output myfile << line; it just creates line of text when you open it in a text editor because their is no newlines.

    Originally in the examples I was reading from, I was reading and writing text files character by character and the files would copy exactly, but using string functions on files means the formatting of the file gets lost.

    I'm not sure if I'm using the right class to be doing text parsing but basically I just want to parse the file so I can change the numerical values in text mode and then re-output the file.
    Code:
    #include <iostream>
    #include <string>
    #include <fstream>
    
    using namespace std;
    
    int main(int argc, char* argv[]) {
      string filepath = "";
      if (argc == 2) {
          filepath = argv[1];
      }
      else {
          cout<< "Error! You did not pass a filepath." <<endl;
          return 1;
      }
    
      char buf[50];
      string bufString = "";
      ifstream filestreamInObject(filepath);
      if (!filestreamInObject.is_open()) {
          cout<< "Error! File was not opened.\n"
                      "Please make sure you passed a valid filepath." <<endl;
          return 1;
      }
      while (!filestreamInObject.eof()) {
            filestreamInObject.getline(buf, sizeof(buf));
            bufString = buf;
            bufString += '\n';
      }
      cout<< "You read from file:\n" << bufString <<endl;
      cout<< "\n\nPress Enter to end this program." <<endl;
      cin.get();
    
      return 0;
    }
    Last edited by Programmer_P; 06-07-2010 at 05:07 PM.

  5. #5
    Registered User
    Join Date
    May 2010
    Posts
    11
    Ok this code read the file but I had to insert an if statement in their or else the files near the end would not be written properly when I did a text file comparison to see if they were exact.

    If I remove the if and the else statement, I get two additional lines and the last line of the original file doesn't get written, but the output file has two (or is it two less?) lines.

    Code:
        while (! myfile.eof() )
        {
          getline (myfile,line);
    	
    	myfile3.open(stuff);
     	if(!myfile.eof())
    	{
    		myfile2 << line;
    		myfile2 << "\n";
    	}
    	else
    		myfile2 << line;
    Last edited by sting777; 06-07-2010 at 05:14 PM.

  6. #6
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by sting777 View Post
    Ok this code read the file but I had to insert an if statement in their or else the files near the end would not be written properly when I did a text file comparison to see if they were exact.

    If I remove the if and the else statement, I get two additional lines and the last line of the original file doesn't get written, but the output file has two (or is it two less?) lines.

    Code:
        while (! myfile.eof() )
        {
          getline (myfile,line);
    	
    	myfile3.open(stuff);
     	if(!myfile.eof())
    	{
    		myfile2 << line;
    		myfile2 << "\n";
    	}
    	else
    		myfile2 << line;
    Why are you trying to write to a file after the end of the file? Do you want to avoid overwriting something in a existing file?

    That's easy...
    Adding to my previous code:
    Code:
    ofstream filestreamOutObject(OUTPUTFILEPATH, ios_base::app); //open file in append mode
    filestreamOutObject << bufString.c_str(); //output the input to file
    Last edited by Programmer_P; 06-07-2010 at 05:23 PM.

  7. #7
    Registered User
    Join Date
    May 2010
    Posts
    11
    Quote Originally Posted by Programmer_P View Post
    Why are you trying to write to a file after the end of the file? Do you want to avoid overwriting something in a existing file?

    That's easy...
    Adding to my previous code:
    Code:
    ofstream filestreamOutObject(OUTPUTFILEPATH, ios_base::app); //open file in append mode
    filestreamOutObject << bufString; //output the input to file
    Sorry the examples I've been using aren't the best and often times don't have enough real world examples of usage, the book I've been reading loves using while loops to write files and that's where I've been getting that from.

    when I don't use the while loop the end of file gets cut off (thelast line or so) but two newlines or a null and a few newlines are added.

    A null and a newline are added. Sec I'll check it out.

    update ... ok I get a null on the last line and then a newline sorry.
    Last edited by sting777; 06-07-2010 at 05:26 PM.

  8. #8
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by sting777 View Post
    Sorry the examples I've been using aren't the best and often times don't have enough real world examples of usage, the book I've been reading loves using while loops to write files and that's where I've been getting that from.

    when I don't use the while loop the end of file gets cut off (thelast line or so) but two newlines or a null and a few newlines are added. Sec I'll check it out.
    Here's a couple of good references you can read for ifstream and ofstream.

    ifstream:
    ifstream - C++ Reference

    ofstream:
    ofstream - C++ Reference

  9. #9
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by sting777 View Post
    Sorry the examples I've been using aren't the best and often times don't have enough real world examples of usage, the book I've been reading loves using while loops to write files and that's where I've been getting that from.

    when I don't use the while loop the end of file gets cut off (thelast line or so) but two newlines or a null and a few newlines are added.

    A null and a newline are added. Sec I'll check it out.

    update ... ok I get a null on the last line and then a newline sorry.
    Ok, if you don't want the null character, do this after every line read from file:

    Code:
    string str = filestreamInBuffer;
    unsigned int nullCharIndex = str.size();
    str.erase(nullCharIndex);
    then add 'str' to bufferStr.
    Last edited by Programmer_P; 06-07-2010 at 05:39 PM.

  10. #10
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    Using eof to control the loop is bad.

    Should use getline as the control
    Code:
    while(getline (myfile,line)){
    }//while
    Woop?

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Programmer_P View Post
    Ok, if you don't want the null character, do this after every line read from file:

    Code:
    string str = filestreamInBuffer;
    unsigned int nullCharIndex = str.size();
    str.erase(nullCharIndex);
    then add 'str' to bufferStr.
    Programmer_P, you can use std::getline and skip using a character buf entirely.

    @OP: What do you mean by null character? Do you mean '\0'? Or something else?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    May 2010
    Posts
    11
    Quote Originally Posted by Elysia View Post
    Programmer_P, you can use std::getline and skip using a character buf entirely.

    @OP: What do you mean by null character? Do you mean '\0'? Or something else?
    See here, this is from ultra compare

    http://s951.photobucket.com/albums/a...hatImean_1.jpg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 12-23-2009, 07:38 AM
  2. Need help with structures
    By yoursport in forum C++ Programming
    Replies: 8
    Last Post: 04-20-2005, 11:59 AM
  3. Ofstream, Ifstream, Searching files for strings?
    By Zeusbwr in forum C++ Programming
    Replies: 10
    Last Post: 04-04-2005, 03:45 PM
  4. problem with getline() file I/O
    By hyperion in forum C++ Programming
    Replies: 4
    Last Post: 12-08-2003, 09:34 AM
  5. Is there anyway to use the getline function with strings?
    By Terranc in forum C++ Programming
    Replies: 4
    Last Post: 12-26-2002, 12:02 PM