hi i have a unknown string in c++ containing "\n" "\t" etc.
say;
string unknown1="\n\t\n\t\n\n\n\n\n";
now I want to print

"\n\t\n\t\n\n\n\n\n"

to the screen explcitly other than a bunch of empty spaces.... how should I do that? remember that I don't know what is in unknown1...

Since \n and \t are treated as one character not 2, near as I can tell you're pretty much much left with looking for those and replacing them with 2 characters in their place:

string unknown1 = "\n\t\n\t\n\n\n\n\n";
for (int i = 0; i < unknown1.size();i++)     
{
    if (unknown1[i] == '\n')
    {
        unknown1.replace(i, 1, "\\n");
        continue;
    }
    if (unknown1[i] == '\t')
    {
        unknown1.replace(i, 1, "\\t");
    }
}
cout << unknown1;

Thanks for answering, however we have further concerns:

The procedure answered has one more porblem... Suppose I don't know that the only possible special character in the file is \n or \t... maybe there are something like \u ? \l ? i think we can't exhaust every possibility right? Is there kind of built in C++ function just to output the corresponding characters?

If I'm not mistaken pretty much all the special characters fall below ASCII code 32. These along with the space are considered whitespace. You could use the isspace function to trap these. Howeve if you don't want to trap spaces you could trap for anything less than a space(i(unknown1[i] < ' ')). The difficulty then becomes in deciphering what characters to replace them with. A map would work well here:

//These are the standard whitespace codes except for space
//'\t'  (0x09)  horizontal tab(TAB)
//  '\n'    (0x0a)  newline(LF)
//  '\v'    (0x0b)  vertical tab(VT)
//  '\f'    (0x0c)  feed(FF)
//  '\r'    (0x0d)  carriage return (CR)

map<char, string> whiteSpace;
whiteSpace['\t'] = "\\t";
whiteSpace['\n'] = "\\n";
whiteSpace['\v'] = "\\v";
whiteSpace['\f'] = "\\f";
whiteSpace['\r'] = "\\r";
string unknown1 = "\n\t\n\t\n\n\n\n\n";
for (int i = 0; i < unknown1.size();i++)     
{
    if (unknown1[i] < ' ')
    {
        unknown1.replace(i, 1, whiteSpace[unknown1[i]]);
    }
}
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.