How to not use "\r" in last "writeline".

Post Reply
arothenberger
Newbie
Posts: 12
Joined: Thu May 29, 2014 10:48 am

How to not use "\r" in last "writeline".

Post by arothenberger »

Hello,
I'm writing a line to a text document and I am using "\r" to make each entry on a new line. However, I don't want to use "\r" on the last entry because I need to write another line without skipping a line. Hopefully this makes sense without posting the whole code.

The text document that I end up with looks like this...
1.Hello my name is Bob.
2.Hello my name is Sam.
3.Hello my name is Jim.
4.
5.There are three total names.

I need it to look like this...
1.Hello my name is Bob.
2.Hello my name is Sam.
3.Hello my name is Jim.
4.There are three total names.

I need to ignore the last "\r" but I will never know how many entries I am writing to the document.

Thanks,
Adam
freddyp
Advanced member
Posts: 413
Joined: Thu Feb 09, 2012 3:53 pm

Re: How to not use "\r" in last "writeline".

Post by freddyp »

It depends on how you are constructing the line that goes into the file. I assume you are in a loop. You could make an exception for the last iteration by checking the loop variable against the length of the array your are looping over. Or after the loop you could remove the last character before appending the final line: make a substring from 0 to the length of the string minus 2 or replace the last character by finding the last character with a regular expression and replacing it by an empty string. I am sure there are other approaches.
bens
Member
Posts: 130
Joined: Thu Mar 03, 2011 10:13 am

Re: How to not use "\r" in last "writeline".

Post by bens »

If the length of the loop can be calculated:

Code: Select all

for ( var i = 0; i != length-1; ++i ) // length - 1 to skip the last line
{
  text += line[i];
  text += '\r';
}
// now handle the last line, without \r:
text += line[length-1];
If the length can't be calculated, you could instead have the first line be an exceptional case, and write the \r as part of the next line:

Code: Select all

text += firstLine();
var currentLine = getNextLine();
while ( currentLine != "" )
{
  text += '\r';
  text += currentLine;
  currentLine = getNextLine();
}
BTW you may want to consider using \n instead of \r. \r is the old Mac way, new Mac files use \n and Windows uses \r\n but handles \n correctly in most cases.
arothenberger
Newbie
Posts: 12
Joined: Thu May 29, 2014 10:48 am

Re: How to not use "\r" in last "writeline".

Post by arothenberger »

It's slightly silly... I was generating two variables to write to a line in a text document. The first line named "text" also contains the "\n" for a new line. Causing that last line to give a new blank line. So my "text2" line always skipped a line.

I fixed it by changing the write line from two lines of writeline(text) and writeline(text2) to writeline(text + text2).

Adam
Post Reply