views:

61

answers:

4

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 << '\\';
         }
         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.

+2  A: 

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).

James McNellis
The code aborts on me even if I corrected it. I edited the post; could you help me again?
danutenshu
A: 

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.

Ignacio Vazquez-Abrams
what do you mean index 1. could you explain further?
danutenshu
The opening quote is at index 0 of the string.
Ignacio Vazquez-Abrams
okay i've corrected as shown above, but if i add the line `cout << sizeof(i);` it outputs 4 no matter what I type in prompt
danutenshu
That's because the `sizeof` operator is giving you the size of the reference/pointer. Perhaps you want `strlen()` or something similar.
Ignacio Vazquez-Abrams
+1  A: 

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++)

TheUndeadFish
+1  A: 

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'
Alex B