c - 未声明错误“信息”(在此函数中首次使用)
问题描述
结构有问题。我该如何声明?我需要执行以下操作:
您的函数将返回一个整数。
- 你的函数应该只接受一个参数(一个数组)。
- 您的函数将询问用户将输入的字符数。然后,在您的函数内部,您将检查该值是否大于或等于 70。如果值大于或等于 70,您将打印出错误消息并返回 1。否则,您将使用循环扫描字符并返回 0。
#include <stdio.h>
struct info {
char name[70];
char lastname[70];
char address[70];
};
void printarray(char name[]) {
int i;
int number;
printf("How many characters will be inputted? \n");
printf("It cannot be more than 70!\n");
scanf("%d", &number);
printf("What is your name? \n");
for(i=0; i<number; i++) {
scanf(" %c", &info.name[i]);
}
return;
}
int main() {
struct info name;
return 0;
}
解决方案
代码有几个缺陷:
该程序应该接收一个 char 数组,而不是一个结构模板。
没有设置将数字与 进行比较的条件
>= 70
。该功能
printarray(char[])
从未使用过。该函数
printarray()
不返回任何内容(即 void),期望返回一个整数1
或者0
不可能返回。return
在函数的最后一行,不是必需的。info
语法中的标识符:scanf(" %c", &info.name[i]); // obviously an error
是类型名称,而不是
info
struct 的实例。
另外:避免使用神奇的数字,当数字不会在任何地方更改时使用常量(例如,在给定的程序MAX
中保持70
整数值)。
重新定义的示例代码如下:
#include <stdio.h>
#define MAX 70
// struct template
struct info {
char name[MAX];
// ...
};
// function declaration
int print_array(info);
int main(void) {
info in;
int exit_code;
// passing a single argument
exit_code = print_array(in);
printf("\nExit code was: %d\n", exit_code);
return 0;
}
// function definition
int print_array(info i) {
int num;
printf("Enter a number (not >= 70): ");
scanf("%d", &num);
if (num >= 70) {
printf("The input exceeds the limit.\n");
return 1;
}
for (int it = 0; it < num; it++)
i.name[it] = getchar();
printf("%s\n", i.name);
// ...
return 0;
}
代码将输出:
Enter a number (not >= 70): 30
Hello world, how are you today? hope you're doing good!
Hello world, how are you toda // rest are truncated
Exit code was: 0
推荐阅读
- python - 让用户将图片上传到我的 kivy 应用
- swift - 根据内容调整 UILabel 高度?
- ruby-on-rails - wkhtmltopdf_binary_gem:语法错误:单词意外(期望“)”)
- java - 如何将 jtextfield 添加到具有绘制组件的 jpanel?
- c++ - 如何将内存静态分配给指向结构的指针数组
- javascript - 我如何使用 adonis js 和 nuxt 以及电子和本地数据库,如 mongoDB 或 Sqlite?
- python - 涉及将 DNA 转录为 mRNA 的家庭作业项目;得到“TypeError:字符串索引必须是整数”
- java - docker compose中的Bitcoinj OverlappingFileLockException
- python - 除了 BaseException as e: 不断抛出错误
- javascript - page.evaluate 返回空值但浏览器控制台返回正确值