简体   繁体   中英

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]); 
    } 
} 
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);

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

It works perfectly fine...

This is wrong:

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

should be:

scanf("%s", str);

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM