So I've been writing a program that takes any input from the command line up until a '.' character, and then prints out the input but with the lines reversed. So:
hello
world.
becomes
world
hello
The problem is supposed to be used to practice linked lists, so I'm using a linked list to store each line of input (string) and then another list to store the lines. So I want to have it so that an incoming character is put at the end of the string list until a '\n' is received and then this line is put at the start of the list of lines. The code I have currently works fine, but it seems to me that the logic is pretty messy. However I can't come up with anything else that works properly.
do {
string->first = string->last = NULL ; // 'empty' the list
while ((c = getchar ()) != '.') {
addToEndOfString (string, c) ; // puts a character at the end of a list of characters
if (c == '\n') break ;
}
addToStartOfList(l, str) ; // puts a pointer to a list of characters at the start of a list of pointers
} while (c != '.');
// print the list
With this I'm also forced to print '\n' when I print out each line, because they are not stored.
Is there a better (cleaner) way of doing the same thing?
EDIT: addToEndOFString
int addToEndOfString ( String *str , char c )
{
Character *a = malloc(sizeof(Character)) ;
a->val = c ;
a->next = NULL ;
if (str->first == NULL) {
str->first = a ;
str->last = a ;
} else {
str->last->next = a ;
str->last = a ;
}
return 0 ;
}
Use fgets