题
我是C的全新,并且正在尝试学习如何使用字符串并使用功能打印它。我看到到处都有示例 while(ch = getchar(), ch >= 0)
, ,但是,一旦我将其纳入一个函数(而不是main()),它就停止工作。现在,它被困在一个无尽的循环中...为什么?
// from main():
// printString("hello");
void printString(char *ch)
{
while (*ch = getchar(), *ch >= 0)
putchar(*ch);
}
解决方案
根据您的描述,您只想:
void printString(char *ch)
{
while(*ch) {
putchar(*ch);
ch++;
}
}
您的原始功能:
void printString(char *ch)
{
while (*ch = getchar(), *ch >= 0)
putchar(*ch);
}
做很多事情:
- 从stdin读取字符
- 存储角色从stdin读到的第一个字符所指向的字符
ch
(如果您传递字符串字面的话,这甚至可能无法正常工作。 - 将角色写入stdout。
- 终止读取字符<0(这在某些平台上不起作用。由于结果存储在char中,因此您无法区分EOF和有效字符。CH应该是INT,因为GetChar(GetChar()返回INT因此您可以检查EOF)
其他提示
getchar()
从STDIN读取用户输入。如果要打印要通过的字符串,则不需要 getchar()
.
让我们一步一步。您已经从stdin读取一个角色的循环,直到达到文件终止。那就是 ch >= 0
测试检查:只要我们获得有效的字符,请继续阅读。为了打印字符串的字符,条件会发生变化。现在有效的角色是任何不是nul的东西('\0'
)。因此,我们将将循环条件更改为:
while (*ch != '\0')
接下来是弄清楚循环主体。 putchar(*ch)
很好;我们将其留在那里。但是没有 getchar()
我们必须弄清楚“获得下一个字符”的等效陈述是什么。
那会 ch++
. 。这进展了 ch
指向字符串中的下一个字符。如果我们将其放在循环的末尾,那么我们将打印一个字符,提前一个空间,然后检查下一个字符是否为非NUL。如果是这样,我们将其打印,提前和检查。
while (*ch != '\0') {
putchar(*ch);
ch++;
}
这里发生的是以下内容:
- 在功能中
main
你打电话printString
用指向字符串“ Hello”的指针 - 这
printString
功能尝试阅读角色getchar()
- 并将该角色保存在“ H”
该语言的规则说,试图改变“ H”是不确定的行为。如果幸运的话,您的程序崩溃了;如果您非常不幸,则该程序将有效。
简而言之: getchar()
用于阅读; putchar()
用于写作。
您想写5个字母:'h','e','l','o'和另一个'o'。
hello ^ ch is a pointer ch *ch is 'h' -- ch points to an 'h'
最后一个“ O”之后有什么? 有! 一个 '\0'
. 。零字节终止字符串。所以尝试一下(与 printString("hello");
) ...
void printString(char *ch)
{
putchar(*ch); /* print 'h' */
ch = ch + 1; /* point to the next letter. */
/* Note we're changing the pointer, */
/* not what it points to: ch now points to the 'e' */
putchar(*ch); /* print 'e' */
ch = ch + 1; /* point to the next letter. */
putchar(*ch); /* print 'l' */
ch = ch + 1; /* point to the next letter. */
putchar(*ch); /* print 'l' */
ch = ch + 1; /* point to the next letter. */
putchar(*ch); /* print 'o' */
ch = ch + 1; /* point to the next letter. What next letter? The '\0'! */
}
或者,您可以在循环中写(并从Main打电话给不同的参数)...
void printString(char *ch)
{
while (*ch != '\0')
{
putchar(*ch); /* print letter */
ch = ch + 1; /* point to the next letter. */
}
}
我只会做 printf("%s",str);
或者 puts(str);