c - 在 C 中为函数设置值

标签 c string reverse

我正在尝试在 C 中做一个反向字符串问题,我知道还有其他方法可以做到这一点,但我很困惑为什么以下解决方案不起作用。 (我会把输出放在下面)

/*Write a function reverse (s) that reverses the character strings. Use it to write a program that reverses its input a line at a time*/
#include <stdio.h>
#define MAXLENGTH 1000

int ngetline(char s[], int lim);
void nreverse(char s[], int index);

main(){
    int len;
    char line[MAXLENGTH];

    while(len = ngetline(line, MAXLENGTH) > 0)
    {
        printf("length: %d\n", len);
        nreverse(line, len);
    }

    printf("%s", line);

    return 0;

}


int ngetline(char s[], int lim)
{
    int c;
    int i;
    for(i = 0; i <  lim -1 && (c = getchar()) != EOF && c != '\n'; ++i)
    {
        s[i] = c;
    }

    if(c == '\n')
    {
        s[i] = c;
        ++i;
    }

    s[i] = '\0';
    printf("i: %d\n", i);
    return i;
}


void nreverse(char s[], int len)
{
    int i, backIndex;
    int halfway;
    char temp;
    backIndex = len - 2;
    halfway = backIndex / 2;



    for(i = 0; i <= halfway; ++i)
    {
        printf("In the for\n");
        temp = s[i];
        s[i] = s[backIndex];
        s[backIndex] = temp;
        --backIndex;
    }
}

这是输出:

./reverseString
entering while
String to be Reversed
i: 22
length: 1

如您在代码中所见,我将长度设置为等于返回 i 的函数 ngetline()。但是当我打印/尝试获取长度时,它返回 1。有人知道为什么会这样吗?谢谢。

最佳答案

这是一个c operator precedence事物。由于关系 (>) 比赋值 (=) 具有更高的优先级,因此它首先被评估,因此您正在分配值 True(或 1) 到变量 len。尝试将作业放在括号中:

while((len = ngetline(line, MAXLENGTH)) > 0)

关于c - 在 C 中为函数设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50032213/

相关文章:

c - 为什么我的写入没有阻塞到这个管道?

c - float 混淆 - 我很困惑 float 说明符是如何出现的

java - 将String(表示十进制数)转换为long

C# 超大字符串操作(内存不足异常)

django - 如何获得通用 View 的反向URL?

c - 位掩码参数命名约定?

c - 打印格式

Java如何限制一行打印的字符数

python - 如何按长度对列表进行排序,然后按相反的字母顺序排序

C 程序用新行反转字符串