-
July 17th, 2013, 07:42 PM
#1
problem with printf in loop
I am having trouble with the printf in this function:
Code:
void print_orig_array(char string_array[MAX_PEOPLE][NAME_SIZE], int ages[MAX_PEOPLE], int length)
{
int counter;
printf("Original list");
printf("\n___________________________\n");
for(counter = 0; counter < length; counter++)
{
printf("%s\t\t\t\t%2d\n", string_array[counter], ages[counter]);
}
}/* end of print_orig_array() */
Here is the output:
Am I missing something with the format specifier? How do I fix the 84 that gets pushed out?
Thanks in advance!
-
July 18th, 2013, 12:24 AM
#2
Re: problem with printf in loop
Hi.
Yo can add more tabs:
Code:
printf("%s\t\t\t\t\t\t%2d\n", string_array[counter], ages[counter]);
or you can add spaces to fit to NAME_SIZE:
Code:
void print_orig_array(char string_array[MAX_PEOPLE][NAME_SIZE], int ages[MAX_PEOPLE], int length)
{
int counter;
printf("Original list");
printf("\n___________________________\n");
for(counter = 0; counter < length; counter++)
{
char name[NAME_SIZE];
int i=0;
int len = strlen(string_array[counter]);
while(i<len) {
name[i] = string_array[counter];
i++;
}
while(i<(NAME_SIZE-1)) {
name[i] = ' ';
i++;
}
name[i] = '\0';
printf("%s\t%2d\n", name, ages[counter]);
}
}/* end of print_orig_array() */
Best regards
-
July 18th, 2013, 08:19 AM
#3
Re: problem with printf in loop
Originally Posted by juanpast
Yo can add more tabs:
Code:
printf("%s\t\t\t\t\t\t%2d\n", string_array[counter], ages[counter]);
I don't see how that should help.
or you can add spaces to fit to NAME_SIZE:
Code:
void print_orig_array(char string_array[MAX_PEOPLE][NAME_SIZE], int ages[MAX_PEOPLE], int length)
{
int counter;
printf("Original list");
printf("\n___________________________\n");
for(counter = 0; counter < length; counter++)
{
char name[NAME_SIZE];
int i=0;
int len = strlen(string_array[counter]);
while(i<len) {
name[i] = string_array[counter];
i++;
}
while(i<(NAME_SIZE-1)) {
name[i] = ' ';
i++;
}
name[i] = '\0';
printf("%s\t%2d\n", name, ages[counter]);
}
}/* end of print_orig_array() */
That would help (except for a small error that makes the code fail to compile), but an equivalent effect can be achieved much simpler by specifying a field width for the string:
Code:
printf("%-47s %2d\n", string_array[counter], ages[counter]);
The trick is to specify the field width as a negative number to left-justify the string in the output.
I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.
This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|