This is probably a simple fix but I can't quite figure it out. How can I find an escaped character in in a string?

E.g.
string str = "abcde\tfghi";

while (str [counter] != '\t') {
	counter++;
}

No, it's reading the backslash and 't' as separate characters.

This is probably a simple fix but I can't quite figure it out. How can I find an escaped character in in a string?

E.g.
string str = "abcde\tfghi";

while (str [counter] != '\t') {
	counter++;
}

Didn't that work?

No, it's reading the backslash and 't' as separate characters.

Why not post a complete and compilable snippet?

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

int main ( void )
{
   int counter = 0;
   string str = "abcde\tfghi";
   while ( str [counter] != '\t' )
   {
      counter++;
   }
   cout << "counter = " << counter << "\n";
   return 0;
}

/* my output
counter = 5
*/

Looks like it works just fine to me.

The problem, Dave, is the string is really string str = "abcde\\tfghi"; At least according to post #3

I'm guessing there is a buffer clearing issue or something like that with strings? I don't know what it could be, but for some reason. The following code does what it's supposed to do, in the first (outer) iteration, and recreates the record using the substring method. But on the second outer loop iteration, the inner while loop stops looping in the middle of a word that isn't the next tab's position.

string record = "abcde\tfghij\tklmno\tpqrs"
while (outerCounter< 16) {
	counter= 0;
	length = record.length();
		
	while (record[counter] != '\\' && record[counter] <= length   ) {
			
		counter++;
	}
		
	if (counter> record.length()) {
		break;
	}
	subRecord = record.substr(0, counter);
		
	counter= counter+ 2;

	record = record.substr(counter, record.length());
        outerCounter++;
		
}

Edited 6 Years Ago by nsjoe: n/a

I personally think you are very confused. string record = "abcde\tfghij\tklmno\tpqrs" There are no \'s in this 22 character string, only TABs. Therefore this loop

while (record[counter] != '\\' && record[counter] <= length ) 
{
    counter++;
}

will run through the entire 22 character string.

You should at lease print out the value of counter just before if (counter> record.length()) { It will probably tell you a lot.

The problem, Dave, is the string is really string str = "abcde\\tfghi"; At least according to post #3

Or taking user/file input, in which case abcdef\tfghi would contain the characters '\' followed by 't' (and not the character literal representing a tab character), which is why I was asking for the actual code. Mentioning "clearing" still leads me to lean in that direction.

Edited 6 Years Ago by Dave Sinkula: n/a

This article has been dead for over six months. Start a new discussion instead.