Question

I am writing the following code to reverse the string, without reversing the words. For e.g. I/P: This is sparta O/P: sparta is This

Here's the code:

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

void main()
{   
    char a[50],b[50];
    int i,j,k,l;
    printf("Enter a string: ");
    scanf("%[^\n]s",a);
    l=strlen(a);
    i=0;j=l-1;
ae: 
    for(i;;i++)
        if(a[i]==' ' || a[i]=='\0')
            break;
    k=i;
    for(j;;j--,k--)
    {
        if(a[k]==' ' || k==0)
            break;
        else
            b[j]=a[k-1];
    }
    if(strlen(b)!=l) goto ae;
    else 
        printf("%s",b);
    getch();
}   

This code runs wihout errors but after accepting the string, it doesn't go further at all. The terminal gets kinda hanged. I don't know whats the problem. Please help.

Was it helpful?

Solution 2

I debugged your program and the problem i found is that your program is entering into a never ending loop.

for(i;;i++)
    if(a[i]==' ' || a[i]=='\0')
        break;

the above loop breaks at i=4 when a[i] was equal to ' '. Later after goto is executed,i is still 4 and when

if(a[i]==' ' || a[i]=='\0')
        break;

is evaluated i remains 4 and therefore again breaks from the loop.Thus leading to a endless loop.

OTHER TIPS

This is an infinite loop if the entered string contains a space.

  1. Iterate over the string a until a[i] == ' '.
  2. k = i;
  3. Immediately break out of the second for loop because a[i] == ' ' and k == i implies a[k] == ' '.
  4. b is uninitialized but strlen(b) != l will be true with high probability and therefore the branch goto ae; will be taken and the infinite loop is closed.

The format string in scanf("%[^\n]s",a); is made up of two parts: "%[^\n]" and "s".

The first part expects a sequence of characters different than '\n' and writes them in the corresponding address.

The second part expects a literal 's' and discards it.

With the input "This is sparta\n" the scanf() isn't terminated. It is still looking for an 's'.

You cannot safely use strlen(b), since the characters in b are not initialized to 0.

So to begin with, change b[50] to b[50] = {0}.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top