mogley
mogley

Reputation: 21

Swap two words in a string using C programming

I am close to finish writing a program to swap two words inputed to a program. If i input "Billy Bob" the output will be "@\300_\377" Something weird like that... I believe there is something wrong with my scanf but not quite sure. Here is what i have so far..

{ int i,j,l;
char str[59];
printf("Enter the string\n");
scanf("%s", &str[59]);
l=strlen(str);
for(i=l-1; i>=0; i--)
{ if(str[i]==' ')
{ for(j=i+1; j<l; j++)
    printf("%c",str[j]);
    printf(" ");
    l=i;
    }
    if(i==0) 
    { printf(" "); 
        for(j=0; j<l; j++) 
            printf("%c",str[j]); 
    } 
} 

Upvotes: 0

Views: 8810

Answers (5)

prathik
prathik

Reputation: 11

Instead of using scanf("%s", &str[59]);, you could use gets(str);.

It works perfectly fine...

Upvotes: 1

perreal
perreal

Reputation: 97948

scanf("%s", &str[59]);

Writes the input at the end of the allocated space. Use the address of the first element:

scanf("%s", str);

but this will give you the first word, so either do:

scanf("%s %s", str1, str2); // str1, str2 are arrays

or use fgets:

fgets(str, 59, stdin);

Upvotes: 3

Danny
Danny

Reputation: 2281

That way of writing the function is somewhat difficult to read. I'm not exactly sure what circumstances you are writing it in but an alternative solution would be to split up the input string by a token, in this case a space, and print out the two strings in the opposite order. An example of the function strtok() can be found here.

Something like this:

char str[] ="billy bob";
char * firstToken;
char * secondToken
firstToken = strtok(str, " ");
secondToken = strtok(NULL, " ");
printf("%s %s", secondToken, firstToken);

Upvotes: 0

Kninnug
Kninnug

Reputation: 8053

You're passing the first address after str to scanf. Change &str[59] to str.

Upvotes: -1

taocp
taocp

Reputation: 23634

This is wrong:

 scanf("%s", &str[59]);  
 //^not reading the str, str[59] is even out of bound

should be:

scanf("%s", str);

Upvotes: 0

Related Questions