Click here to Skip to main content
15,889,808 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have this code for converting a string from L to R to R to L but I think something is wrong it - given an input I get "smilies" as an output. Why?
C#
#include <stdio.h>
#include <string.h>
#define MAXLINE 100

int main()
{
    char s[MAXLINE];
    int c, i, j;
    printf("Input string: \n");
    for(i = 0; i < MAXLINE - 1 && (c = getchar() != EOF) && c != '\n'; i++)
        s[i] = c;
    if (c == '\n')
    {
        s[i] = c;
        i++;
    }
    s[i] = '\0';
    printf("%s\n", s);
    for(i = 0, j = strlen(s) - 1; i < j; i++, j--)
    {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
    printf("%s\n", s);
    return 0;
}
Posted
Updated 23-Apr-15 18:43pm
v4
Comments
PIEBALDconsult 24-Apr-15 0:18am    
"Can it be modified somehow?"
Yes, I'd use an editor.
What seems to be the problem?
Sergey Alexandrovich Kryukov 24-Apr-15 0:20am    
"Something is wrong" is not informative at all. You did not even tag what is it? C? C++?
Sorry, the post makes little to no sense.
—SA

1 solution

If you run your code in the debugger, and put a breakpoint in the first loop:
C++
s[i] = c;
Then a quick look at your variables will show you the value of "c" is "1" - regardless of the key you press!

And then it's obvious: it's an operator precedence problem.
Because "Not Equals" has a higher priority than "Assignment" this part:
C++
(c = getchar() != EOF)
Is evaluated to mean
If getchar() is not EOF assign "1" to "c", otherwise assign "0" to "c"
Rather than
Assign the value returned by getchar() to "c", and then check if it is an EOF

Just change the brackets from this:
C++
for(i = 0; i < MAXLINE - 1 && (c = getchar() != EOF) && c != '\n'; i++)
To this:
C++
for(i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; i++)
And it'll work.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900