Dart Feld
Dart Feld

Reputation: 41

removing a zero width character in c++?

I'm working on a c++ file and I've encountered an interesting problem. I'm outputting strings into a text file (using ofstream) and I have the following lines.

void InstructionWriter::outputLabel(string s){
string sLabel;
sLabel = s;
sLabel.erase(remove(sLabel.begin(), sLabel.end(), ' '),sLabel.end());

sLabel = "(" + function + "$" + sLabel + ")\n" ;
outputFile << sLabel;
}

The problem is during the txt file it outputs.

When I head to the text file where outputLabel was run, highlighting the line counts the characters +1 character. that +1 is "invisible." Highlighting the line won't select it. The only way to fix it is to start deleting from the right. After you hit the ')' I'll notice that I hit delete again but the cursor didn't move and it seems like nothing got deleted.

I think It's sneaking in a zero width character but I don't know how to strip that from the string, does anybody have any ideas on what functions to look into?

@smac89

terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::_M_replace
0

That is what the terminal threw at me after running that command you mentioned.

Upvotes: 0

Views: 545

Answers (2)

Ali Tavakol
Ali Tavakol

Reputation: 439

Instead of sLabel.erase(remove(sLabel.begin(), sLabel.end(), ' '),sLabel.end()); please try this:

std::string from = " ", to = "";
size_t start_pos = 0;
while ((start_pos = sLabel.find(from, start_pos)) != std::string::npos) {
  sLabel.replace(start_pos, from.length(), to);
  start_pos += to.length();
}

Because the string is UTF-8 encoded; and You cannot rely on individual bytes. Manipulate sub-strings only.

Upvotes: 0

Dart Feld
Dart Feld

Reputation: 41

Everyone, I was able to figure it out.

per Smacs comment, I uploaded the output text file to a binary editor. oddly enough, I found an 0D before the newline character that I manually put in.

I used a regex replace on the string and now it's not adding that 0D character in the string.

Thanks for all the tips.

Upvotes: 0

Related Questions