When I am given "d""\"/""b"
, I need to print out the statement character for character. (d, b, a slash, a backslash, and 5 quotes) in C++. The only errors that show now are the lines if(i.at(j)="\\")
and else if(i.at(j)="\"")
. Also, how should the outside double apostrophes be excluded?
#include <iostream>
#include <cstdlib>
using namespace std;
int main (int argc, const char* argv[] )
{
string i= argv[1];
for (int j=0; j>=sizeof(i)-1; j++)
{
if(i.at(j)=='\\')
{
cout <&l开发者_如何学运维t; '\\';
}
else if(i.at(j)=='\"')
{
cout << '\"';
}
else
{
cout << i.at(j);
}
}
return 0;
}
*Revision - OK so I corrected the double apostrophes to single apostrophes but the code always aborts on me.
std::string::at()
returns a char
, not a std::string
, so you need to use character literals (delimited by single quotes, '
), not string literals (delimited by double quotes, "
). e.g.,
i.at(j) == '\\'
Note also that you are using assignment (=
) and not equality comparison (==
) in your if
statements (this is a common, pernicious error).
You've goofed up your equality testing (==
, not =
).
Also, start at index 1, and go until 1 less (2 less, by index) than the length of the string.
Your for loop for (int j=0; j>=sizeof(i)-1; j++)
is incorrect for two reasons.
First, you would want a less-than or less-than-or-equal comparison in your loop. As it's written now, j
starts at zero, which is not greater than sizeof(i)-1
. Thus your loop aborts immediately.
Second, sizeof(i)
is not what you want to compare against anyway. That expression gives the size of a string object, not the size of the actual string contained by the object. You want i.size()
With these changes, your loop would be for (int j=0; j<=i.size()-1; j++)
What you are doing is unnecessary. Escaping is only needed in string literals in your code. If you print argv[1]
character-by-character, you will get the string as is.
std::cout << argv[1];
If you are not getting the correct result, this means escaped sequences are first processed by the shell. You can avoid it in many shell. E.g. in bash you have to pass your argument with single quotes:
bash$ ./program 'd""\"/""b'
精彩评论