JunM
JunM

Reputation: 7160

NSLog default break line

I am very new to Objective-C and I am starting to learn simple things. In this case, I want to create a pyramid using the * symbol.

Problem: Everytime * is printed, it includes a line break. How can I get rid of it to create a pyramid look? I thought I had to add \n to cause a line break in the Break line text I added.

Right now, I have this code to create a pyramid:

    //Pyramid
    int a,b;
    int x=5;

    for(a = 1; a <= x; a++){

        for(b=1; b<=a; b++){
            NSLog(@"*");
        }

        NSLog(@"Break line");

    }

Result:

2014-02-23 10:44:35.264 Pyramid[614:303] *
2014-02-23 10:44:35.266 Pyramid[614:303] Break line
2014-02-23 10:44:35.267 Pyramid[614:303] *
2014-02-23 10:44:35.267 Pyramid[614:303] *
2014-02-23 10:44:35.267 Pyramid[614:303] Break line
2014-02-23 10:44:35.268 Pyramid[614:303] *
2014-02-23 10:44:35.268 Pyramid[614:303] *
2014-02-23 10:44:35.269 Pyramid[614:303] *
2014-02-23 10:44:35.269 Pyramid[614:303] Break line
2014-02-23 10:44:35.269 Pyramid[614:303] *
2014-02-23 10:44:35.270 Pyramid[614:303] *
2014-02-23 10:44:35.270 Pyramid[614:303] *
2014-02-23 10:44:35.270 Pyramid[614:303] *
2014-02-23 10:44:35.271 Pyramid[614:303] Break line
2014-02-23 10:44:35.271 Pyramid[614:303] *
2014-02-23 10:44:35.272 Pyramid[614:303] *
2014-02-23 10:44:35.272 Pyramid[614:303] *
2014-02-23 10:44:35.272 Pyramid[614:303] *
2014-02-23 10:44:35.273 Pyramid[614:303] *
2014-02-23 10:44:35.273 Pyramid[614:303] Break line

Upvotes: 0

Views: 430

Answers (2)

Dave Wood
Dave Wood

Reputation: 13333

NSLog always outputs a newline at the end, as well as other info at the start.

You can use printf("*"); to output to the console without a newline. Include \n when you want a newline.

for (NSUInteger outerIndex = 1; outerIndex <= 5; ++outerIndex) {
    for (NSUInteger innerIndex = 1; innerIndex <= outerIndex; ++innerIndex) {
        printf("*");
    }

    printf("\n");
}

Upvotes: 5

Flipper
Flipper

Reputation: 2609

As stated in the comments, NSLog will always only output one line and you will not be able to avoid that like you can do in Java. Alternatively you should look into building strings (such as described here: Shortcuts in Objective-C to concatenate NSStrings).

An example:

//Pyramid
int a,b;
int x=5;

for(a = 1; a <= x; a++){
    NSMutableString *string = [NSMutableString string];
    for(b=1; b <= a; b++){
        [string appendString:@"*"];
    }

    NSLog(@"%@", string);
}

Upvotes: 1

Related Questions