I'm stuck on a piece of code I have been working on. I need to receive N number of inputs using argc and argv[] parameters. Then the N number of inputs will allow the user to enter that many sentences. For every sentence, my code should reverse every word in the sentence. Currently, my code will take in the N value and sentence, but won't print the reverse sentence. Instead, it prints a blank line.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 80
void get_input(char *line){
fgets(line, SIZE, stdin);
char *ptr = strchr(line, '\n');
if (ptr){
*ptr = '0'; }
}
void reverse(char *line){
char copy[SIZE];
char word[SIZE];
memset(copy, 0, SIZE);
int line_len = strlen(line);
int word_len = 0;
int i;
for(i=line_len; i<=0; --i){
if(line[i] == ' ' && word_len > 0){
memset(word, 0, SIZE);
strncpy(word, line + i + 1, word_len);
strcat(copy, word);
strcat(copy, " ");
word_len = 0;
}else if(isalnum(line[i]) || line[i] == '\'')
{word_len++;}
}
if(word_len>0){
memset(word, 0, SIZE);
strncpy(word, line, word_len);
strcat(copy, word);}
strcpy(line, copy);
}
int main(int argc, char *argv[]){
int N = (int)strtol(argv[1], NULL, 10);
if(N<0){
printf("ERROR: Please provide an integer greater than or equal to 0\n");
return 0;
}
if(N>SIZE){ printf("ERROR: Please provide an integer less than or equal to 80\n");
return 0;
}
char line[SIZE];
int i;
for(i=0;i<N;i++){
get_input(line);
reverse(line);
printf("%s\n", line);
}
return 0;
}
Example Input:
1
The fox jumped over a log
Example desired output:
log a over jumped fox The
Current output: