i have a string which is giving me problems. when i put it into a textfile, it puts the cursor onto the nextline. i assume because there is a \n at the end of the string, but when i cout the string, the newline character isnt there (well, the console doesnt put the next peice of text on the newline). is there someway i can stop it adding this newline? because its causing my program to crash later on.

Recommended Answers

All 15 Replies

Show the line(s) that you are using to put it into the text file. You may be adding endl to the end of the line when you don't want to. If you're then, reading it back into a string, something like getline reads to the end of the line and discards the newline character.

ofstream input(target.c_str(), ios::app|ios::ate);
input << name;
input << data;
input.close();

the newline comes after data. i just want to add it to the end of the file without having the newline. basically i first fill data using a function i wrote to cycle a different file and find a specific line. it then returns that line from the file and puts it into data. i use getline() in that function to take the line. anyway i want this to put it into a new file, which it does, but shoves a newline in there too

ive still been trying to solve this problem but no success. why is it the you can append a text file with a "\n" and it will put the cursor on a newline, but you cant append it with a "\b" so it will backspace? is there anyway i can just get rid of this thing its annoying me and crashing my program.

Why don't you just get rid of the "\n" in data before writing it into target?

data=data.substr(0,data.length()-1); //if data is of std::string type

because i didnt know how to. however the plot does thicken. It has removed the last char of the string, but the cursor still goes onto the next line. is this just how ofstream works?

Not from what i know.Maybe you could post some more code.

#include <fstream>
#include <string>
using namespace std;

int main()
{
    string word1 = "dog\n\n";
    string word2 = "dog\n";
    string word3 = "dog";
	
    ofstream out("dog.txt", ios::app|ios::ate);
    out << word1 << word2 << word3;
    out.close();
    ofstream out2("dog.txt", ios::app|ios::ate);
    out2 << word1 << word2 << word3;
    out2.close();

    return 0;
}

Results:

dog

dog
dogdog

dog
dog

There's no '\n' in the file that wasn't part of the string, as evidenced by the fourth line and by the file size (if you just write "dog" the file will be 3 bytes in length).

but the cursor still goes onto the next line. is this just how ofstream works?

"Cursor"? What cursor? There are stream pointers in ofstream, but a "cursor" sounds like you're opening the file in a word processor or something. Some word processors will automatically put an extra newline at the end when they open a file without one, but that has nothing to do with the C++ program. Be aware that if you open a file in a text editor/word processor, then immediately resave it, the file may be changed.

of course. this is how im filling data. im sorry about my poor use of variable names. determine2() is a function i wrote which checks a string for a substring and returns the string. removefrom() removes a substring from a string. when i cout Data, it doesnt put the cursor on the nextline, so im completely stumped as to why it should do this in the textfile. ill try adding a set string in place of data, to see if that works and let you know. ive tried to omit the pointless code.

data = getfile2( "pathtothetextfile.txt", datatoidentifywhichlinetoretrieve, int mode, "thisisjunkinthismode");

string getfile2(string file, string infilename, int mode, char print)	

{
int filecounter = 0;
int counter = 0;
string temp = "";
string temp2 = "";
int checker = 1;
char f;
int cast;
int j = 0;
string retdata;
string notfound = " not found";

if (mode == 2)
{
         ifstream data( file.c_str() , ios::in);
         while (getline(data, temp))
         {
                         if (determine2(temp, infilename, 0) == infilename)
                         {
                         temp = removefrom(temp, infilename);
                         data.close();
                         return temp;
                         }
         
         }
         cout <<"'"<< infilename <<"'";
         return notfound;
}

ok, the problem im having is that when i put text into my textfile, i first put a "\n" and then the data. it works fine and everything is dandy. but in this occasion, it is putting the "cursor" (i dont care what you call it, the little vertical line that blinks in notepad) onto the next line. that means that when more data is added, there is a blank space between two lines of writing, and when i cycle through each line in a function and it hits this blank space, it crashes. im using notepad, and it is not changing my textfile, the only way i can prevent the crash is to manually delete the newline using backspace before saving it.

ok, the problem im having is that when i put text into my textfile, i first put a "\n" and then the data. it works fine and everything is dandy. but in this occasion, it is putting the "cursor" (i dont care what you call it, the little vertical line that blinks in notepad) onto the next line. that means that when more data is added, there is a blank space between two lines of writing, and when i cycle through each line in a function and it hits this blank space, it crashes. im using notepad, and it is not changing my textfile, the only way i can prevent the crash is to manually delete the newline using backspace before saving it.

ofstream will output exactly what is in the string (except that if you're using Windows, it changes '\n' to '\r\n'), so if you are writing an extra '\n' at the end that screws everything up, the solution is to not write that extra '\n'. If the extra '\n' is there, it's because you wrote it. ofstream didn't do it on its own. Writing a backspace after the extra newline isn't going to work. The file length is still going to be too long.

I know of no way to "truncate" a file using standard C++, which doesn't mean it doesn't exist. The only way I know is to reopen it and overwrite the file so it doesn't write the extra '\n'.

But the best way to do it is that if you don't want the extra '\n', change the program so it isn't written.

no im not putting an "\n" after everything i put in the textfile, im putting it before anything i put in the textfile. if i remove the /n, everything will be written on a single line, which i dont want, for practicality reasons. im sure such a powerful language as c can do such a simple task. all i want to do is move the end of the file

i am a line in a file
i am the second line<------(to here)
<------ (from here)

>> im sure such a powerful language as c can do such a simple task. all i want to do is move the end of the file

I didn't say it couldn't do it. I said that (to the best of my knowledge) there is no STANDARD way of doing it. There are Operating System specific ways of doing it and there are probably external libraries that do it. A google for "C++ ostream truncate file" seems to back this up, but it also offers alernatives in some of the threads.

i am a line in a file
i am the second line<------(to here)
<------ (from here)

If this is your file, then the last character you wrote was a '\n'. Run the program I posted and you'll note that it does not have the trailing newline. So you have an excess newline in there at the end. An earlier post explains how to truncate a string that has a newline in it if that is the problem. But if the file looks like you are posting it, then you wrote an extra newline at the end, either on its own or as part of a string.

i understand what you are saying, but in debugging, im using cout to print the string, but it doesnt cout a newline. i open up the textfile and there it is, crystal clear. delete it, and no crash. it is so frustrating.

>> it is so frustrating.

I hear you. It's in there, somewhere, though. It has to be. Without seeing the file and all the code, I have no idea where, but here's a little test you can use to check things quickly to make sure things are as they seem when debugging. An addition to my last program. Call the function and make the assertion whenever you assume that the file doesn't end with a newline. If the assertion fails, you've found the problem. Good luck.

#include <fstream>
#include <iostream>
#include <string>
#include <cassert>
using namespace std;


bool NewlineEndsStream(ofstream& outs, const char* filename)
{
    assert(outs.is_open());
    int pos = outs.tellp();
    if(pos <= 0)
    {
        return false;
    }
	
    outs.close();
    ifstream ins(filename);
    ins.seekg(pos - 1);
    char lastChar = ins.get();
    ins.close();
    outs.open(filename, ios::app|ios::ate);
    outs.seekp(pos);
    return (lastChar == '\n');
}


int main()
{
    string word1 = "dog\n";
    string word2 = "dog";
	
    ofstream out("dog.txt", ios::app|ios::ate);
    assert(!NewlineEndsStream(out, "dog.txt"));
    out << word2;
    assert(!NewlineEndsStream(out, "dog.txt"));
    out << word2;
    assert(!NewlineEndsStream(out, "dog.txt"));
    out << word1;
    assert(!NewlineEndsStream(out, "dog.txt"));  // assertion will fail here
    out.close();
	
    return 0;
}

ok guys, i cant isolate the specific problem but i managed to find a way around it now to avoid the crash. mabye ill look into it further later but for now i have to start writing again cus ive been debugging for 3 days. Thanks for your help guys!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.