如何转换字符串 [英] How to convert a string

查看:41
本文介绍了如何转换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码用于将字符串从L转换为R到R转换为L但我觉得有些不对劲 - 给定输入我得到smilies作为输出。为什么?

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?

#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;
}

推荐答案

如果在调试器中运行代码,并在第一个循环中放置一个断点:

If you run your code in the debugger, and put a breakpoint in the first loop:
s[i] = c;

然后快速查看变量会显示c的值为1 - 无论您按哪个键!



然后很明显:这是运营商优先问题。

因为不等于的优先级高于分配这一部分:

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 = 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:

for(i = 0; i < MAXLINE - 1 && (c = getchar() != EOF) && c != '\n'; i++)

对此:

To this:

for(i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; i++)

它会起作用。


这篇关于如何转换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆