Problem with For Loop

1
2
3
4
5
6
7
#include <iostream>

int main(void) {
    for(int i = 0; i < 4; ++i)
        std::cout << "ABCD" + i << '\n'; 
    return 0;
}

I'm trying to use a single for loop to print "ABCD" while removing a character from the end each iteration. The for loop is obviously removing the character from the beginning of the string literal ("ABCD"+0 results in "A" being removed, and so on). What is a way to get around this? I know, there are much easier ways to accomplish this, but this is how I would like it done. Please, do not post any code, just give me hints.

Thanks. =)


I have not understood what you want.
By the way you are not removing any character from the string literal and you may not remove characters from any string literal. String literals in C++ have type const char[] and the C++ standard supresses any changing of a string literal.
What you are doing is outputing sequentially characters of the string literal by using the pointer arithmetic. The expression "ABCD" is converted to the pointer to the first character of the string literal. So "ABD" + 0 is the pointer to the first character, "ABCD" + 1 is the pointer to the second character and so on.
Last edited on
it's related to this

http://cplusplus.com/forum/beginner/80394/

basically, is it possible to do it with only one loop, when "ABCD" is a string literal, not a string?
Output:
1
2
3
4
ABCD
ABC
AB
A

Well, I guess I had some of what it was doing correct. Does the output clear anything up?

it's related to this

http://cplusplus.com/forum/beginner/80394/

basically, is it possible to do it with only one loop, when "ABCD" is a string literal, not a string?

Yes, you got it. I always try to out-do others when it comes to coding.
Last edited on
Topic archived. No new replies allowed.