跟随CS50教程写uppercase程序时遇‘undeclared identifier 'i'’编译错误
问题解决:undeclared identifier 'i' 错误
错误根源
你的代码里for循环末尾多了一个多余的分号:
for (int i = 0; i < strlen(s); i++); // 这个分号是问题所在
这个分号会让for循环的循环体变成空语句,后面的{}块会被视为独立代码块。由于i是在for循环的初始化部分声明的,作用域仅局限于for循环本身,独立块里的i就成了未声明的标识符,因此编译器报错。教程里的代码没有这个分号,所以能正常编译。
修正后的代码
#include <cs50.h> #include <stdio.h> #include <string.h> int main(void) { string s = get_string("Before: "); printf("After: "); // 移除for循环末尾的分号 for (int i = 0; i < strlen(s); i++) { if (s[i] >= 'a' && s[i] <= 'z') { printf("%c", s[i] - 32); } else { printf("%c", s[i]); } } printf("\n"); }
额外优化提示
每次循环调用strlen(s)会重复计算字符串长度,可提前将长度存储以提升效率:
int len = strlen(s); for (int i = 0; i < len; i++)
内容的提问来源于stack exchange,提问作者Sorites
相关产品推荐
相关产品推荐

