我正在尝试在 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/