I am trying to write a program that reverses words in a sentence, the code is able to do that but also prints gibberish in between. (see below code for sample)
#include <stdio.h>
#define MAX_VALUE 50
int main(){
char c[MAX_VALUE],
b[MAX_VALUE];
int i = 0, j = 0;
while ((c[i] = getchar()) != '\n'){
i ;
}
for(i = MAX_VALUE; i >= 0; i--){
if (c[i] == ' '){
for(j = i 1; j < MAX_VALUE; j ){
if (c[j] != ' '){
printf("%c", c[j]);
}
else{
break;
}
}
printf(" ");
}
}
while (c[i] != ' '){
printf("%c", c[i]);
i ;
}
}
Loop goes backwards when it detects a space it prints the word until it finds another space then goes backwards again from where it left off last
The input and output expected:
input: test a is this
output: this is a test
What I get:
input: test a is this
output:
this
`����l�, �D �=� is a test
CodePudding user response:
When you set up your initial for loop you set i to MAX_VALUE which is out of bounds for a char[MAX_VALUE] array, where the last index would be MAX_VALUE - 1
CodePudding user response:
This for loop
while ((c[i] = getchar()) != '\n'){
i ;
}
can write outside the array c
and store the new line character '\n'
in the array.
This outer for loop
for(i = MAX_VALUE; i >= 0; i--){
is incorrect because the user can enter a string that contains less than MAX_VALUE
symbols.
And it is not enough to check this condition
if (c[i] == ' '){
because the leading spaces can be absent in the entered string. So you need to check also whether i
is equal to 0
. Otherwise the first word will not be outputted.
The inner for loop
for(j = i 1; j < MAX_VALUE; j ){
again is incorrect by the same reason of using MAX_VALUE
in the condition.
Pay attention to that the array b
char c[MAX_VALUE],
b[MAX_VALUE];
is not used in your program.
Using your approach I can suggest the following solution to output words of a string in the reverse order shown in the demonstrative program below.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main( void )
{
const char *s = "test a is this";
for( size_t i = strlen( s ); i != 0; )
{
while ( i != 0 && isblank( ( unsigned char )s[i-1]) )
{
putchar( s[--i] );
}
size_t j = i;
while ( j != 0 && !isblank( ( unsigned char )s[j-1]) )
{
--j;
}
if ( j != i )
{
size_t last = i;
i = j;
while ( j != last )
{
putchar( s[j ] );
}
}
}
putchar( '\n' );
}
The program output is
this is a test