I want to read inputtext.txt line by line and reverse the order of words in each line and print them out (input: hello world,output: world hello). With this code my output is all messed up and I get a runtime error #2 saying the stack around my array "string" is corrupted. I tried resetting the strings to null after each while loop iteration but I still get the same error. Does anybody have any suggestions to get rid of the runtime error or help the code run more smoothly?
int main() {
FILE *inp,*outp; //file input and output
int i,wordcount; //define counter variables
int k = 0,j=0;
char string[200]; //define string to scan sentence into
char words[20][20]; //2D string for each word in the sentence
inp = fopen("inputtext.txt", "r");
outp = fopen("output.txt", "w");
if (inp == NULL) {
printf("File not found.\n");
}
else {
while (!feof(inp)) {
fgets(string, 1000, inp);
printf("GOT SENTENCE\n");
for (i = 0; string[i] != '\0'; i++) {
if (string[i] == ' ') {
words[k][j] = '\0';
k++;
j = 0;
}
else
{
words[k][j] = string[i];
j++;
}
}
words[k][j] = '\0';
wordcount = k;
for (i = wordcount; i >= 0; i--) {
printf("%s ", words[i]);
}
printf("\n\n");
}
}
return 0;
}