ARTAGE ARTAGE - 3 months ago 9
C Question

Print two strings

I want to print two strings in console

int k = 3;
for (int i = 0; i < k; i++)
{
printf("\ra: %d\n\rb: %d", i*2, i*3);
}


I want to get this result:

a: 4
b: 6


But I get:

a: 0
a: 2
a: 4
b: 6

Answer

The reason why you are getting that output is that you have just one \r before a, but \n\r between a and b in the:

printf("\ra: %d\n\rb: %d", i*2, i*3);

Every cycle, the cursor returns to the beginning of line where b is and it writes OVER it, with new value for a :

1st    2nd     3rd run
a=0    a=0    a=0
b=0    a=2    a=2 
       b=3    a=4
              b=6

since that is quick, you can see only the last one. It's really not clear what you wanna do, but if you need only the output of the last run, you can write the printf after the cycle:

for (int i = 0; i < k; i++)
{
...
}
printf("\r\na: %d\n\rb: %d", i*2, i*3);
Comments