【发布时间】:2017-10-16 10:48:41
【问题描述】:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
//ask user for input
string s = get_string();
//make sure get_string() returned a string
if(s != NULL)
{
//iterate over the characters one at a time
for(int i = 0, int n = strlen(s); i < n; i++)
{
//print i'th character in s
printf("%c\n", s[i]);
}
}
else
{
//tell the user that their input is not a string
printf("Sorry, no good\n");
}
}
编译器抱怨这一行:
for(int i = 0, int n = strlen(s); i < n; i++)
因为我用int声明了整数n来定义类型。
程序编译得很好:
for(int i = 0, n = strlen(s); i < n; i++)
为什么i 是int 是必需的/良好的形式,但在这个例子中n 不是?
【问题讨论】:
-
语句
int i,n;(无论是否在for循环中)声明了两个变量(而int i, int n;是不正确的[也在任何地方])。在这里,OP 也恰好在初始化它们。 -
@Eimantas 一点也不。
-
如果您有兴趣,可以联系cs50 stack exchange。
-
@maraguida 啊!谢谢,我不知道!
标签: c for-loop declaration cs50