printf formatting

adjust printf argument for desired output format

Page 1 of 1

1 Replies - 616 Views - Last Post: 20 November 2008 - 09:10 PM Rate Topic: -----

#1 dark_pun  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 06-November 08

printf formatting

Post icon  Posted 20 November 2008 - 08:43 PM

This seems like it should be really easy but I can't get my formatting correct in my output. My code executes properly. Here is my code

#include <stdio.h>
#include <string.h>

#define NUMSTR 50
#define STRSIZ 80

int sort_str(char *list[], int min_sub, int max_sub);
void select_str(char *list[], int n);

int main(void)
{
int num_str, i;
char string[NUMSTR][STRSIZ];
char *alpha[NUMSTR];


printf("Enter number of strings (0 to 50)\n> ");
scanf("%d", &num_str);
printf("Enter %d strings on separate lines\n", num_str);

getchar();
for (i=0; i<num_str;++i) {
fgets(string[i], 50, stdin);
alpha[i] = string[i];
}

select_str(alpha, num_str);


printf("\n\n%-30s%5c%-30s\n\n", "Input Strings", ' ', "Sorted in length");
for (i=0; i<num_str; ++i) {
printf("%s", string[i]);
printf("								   %s", alpha[i]);
}
return(0);
}


int 
sort(char *list[], int min_sub, int max_sub)
{
int first, i;

first = min_sub;
for (i=min_sub+1; i<=max_sub; ++i)
	if(strlen(list[i])<strlen(list[first]))	   
	   first = i;

return(first);
}


void
select_str(char *list[], int n)
{
int fill, index_of_min;
char *temp;

for (fill=0; fill<n-1; ++fill) {
index_of_min = sort(list, fill, n-1);

	if (index_of_min != fill) {
		temp = list[index_of_min];
		list[index_of_min] = list[fill];
		list[fill] = temp;
	}
}
}



and here is my current output
Enter number of strings (0 to 50)
> 5
Enter 5 strings on separate lines
hey
hello
hi
how are you today?
I am well.


Input Strings					  Sorted in length			  

hey
								   hi
hello
								   hey
hi
								   hello
how are you today?
								   I am well.
I am well.
								   how are you today?



and how it must be formatted...

Enter number of strings (0 to 50)
> 5
Enter 5 strings on separate lines
hey
hello
hi
how are you today?
I am well.

Input Strings					  Sorted in length			  

hey								hi
hello								hey
hi							hello
how are you today?						I am well.
I am well.						 how are you today?



correction on the "must be formatted" code box: The output under 'sorted in length' must be lined up

This post has been edited by dark_pun: 20 November 2008 - 08:42 PM


Is This A Good Question/Topic? 0
  • +

Replies To: printf formatting

#2 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: printf formatting

Posted 20 November 2008 - 09:10 PM

fgets() includes the line terminator in the string it returns. You need to replace the newlines with nulls.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1