我是昨天的C新手,我正在尝试创建一个需要10个字符的循环,然后打印出其中有多少"a".无论字符串中有多少"a",它都打印出来0.任何帮助都会非常感激.
#include <stdio.h>
#include <string.h>
int main()
{
char string[10];
int c = 0;
int loop = 0;
printf("Enter a string\n");
gets(string);
for (loop = 0; loop >10; ++loop)
{
if (string[c] = 'a')
{
++c;
}
}
printf("A occurs %d times in the entered string.\n",c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我想你应该再读一遍for循环如何工作,
for (loop = 0; loop >10; ++loop)
^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
你的这种情况从一开始就是假的,loop = 0不是>10.因此for循环永远不会执行.
另外,当您在for循环内部进行比较时,您使用loop变量来迭代字符string.并且,要比较==使用,=是赋值运算符.所以,
if (string[c] = 'a')
Run Code Online (Sandbox Code Playgroud)
这应该是
if (string[loop] == 'a')
Run Code Online (Sandbox Code Playgroud)
在我读过的一本非常好的书中,写的是为了避免这种错误,总是以其他方式使用比较,例如,
if ('a' == string[loop])
Run Code Online (Sandbox Code Playgroud)
即使你输入错误而=不是代替==,你也会收到错误.
作为旁注,请勿使用gets()功能.它已被弃用.您可以阅读有关Morris蠕虫的信息,了解gets()可能产生的影响.