我不知道如何使用scanf并获取它的输入,用于输入函数readBigNum我要创建数组,直到用户输入Enter并且我想编写一个函数将其分配到数组并返回大数字的大小 我希望readBigNum具有char * n但我无法将其与我的函数相关联
#include <stdio.h>
int readBigNum(char *n)
{
char msg[100],ch;
int i=0;
while((ch=getchar())!='\n')
{
if(ch!='0'||ch!='1'||ch!='2'||ch!='3'||ch!='4'||ch!='5'||ch!='6'||ch!='7'||ch!='8'||ch!='9')
return -1;
msg[i++]=ch;
}
msg[i]='\0';
i=0;
return i;
}
int main()
{
const char x;
const char n;
n=scanf("%d",x);
int h=readBigNum(&n);
printf(h);
}
答案 0 :(得分:1)
如果我理解你的问题,你想要实现一个函数,它将从stdin中读取数字,并将它们存储在缓冲区中。如果遇到非数字,则要返回-1。如果遇到换行符,则需要返回已读取的字符数。如果这是正确的,您可能希望代码看起来如下所示:
#include <stdio.h>
int readBigNum(char* n)
{
char ch;
int i=0;
while ((ch = getchar()) != '\n') {
if (ch < '0' || ch > '9') {
return -1;
}
n[i++] = ch;
}
n[i] = '\0';
return i;
}
int main(void) {
char buf[100];
int bytes = readBigNum(buf);
printf("%s\n", buf);
printf("%d\n", bytes);
};
与您的实施的主要区别
malloc
和free
。即使这样,您也可能会面临缓冲区溢出的风险,并且可能需要采取额外的预防措施来防止这种情况发生。i
设置为0。原始代码永远不会返回-1
(出错时)或0
以外的值,这似乎不是意图。scanf
。鉴于您对要完成的内容的描述,使用scanf
似乎并不合适,但是如果您提供有关您调用它的原因的更多信息,则可能有助于通知此答案。printf
调用不正确,已更新以打印返回的字节数,并添加了额外的printf
调用以打印更新的缓冲区。答案 1 :(得分:0)
请注意,getchar()
会返回int
类型,而不是char
。这是因为函数可能返回EOF
(定义为没有特定值的负整数)。
此外,对于处理缓冲区的函数,最好采用一个描述数组大小的额外参数。这有助于减少缓冲区溢出,因为您知道可以走多远。使用现有功能,如果用户输入的字符超过100个,则缓冲区溢出。
#include <stdio.h>
#include <ctype.h>
int readBigNum(char *n, size_t len)
{
int ch;
int i = 0;
// we make sure 'i' is less than 'len - 1' to leave space for '\0'
while((ch = getchar()) != EOF && i < (len - 1))
{
if (ch == '\n') // stop on linefeed
break;
else if (!isdigit(ch))) // abort on invalid character
return -1;
else
n[i++] = (char) ch;
}
msg[i] = '\0';
return i;
}
int main(void)
{
char buf[100];
int result = readBigNum(buf, sizeof buf);
if (result > 0)
printf("Length %d : %s\n", result, buf);
else
printf("Invalid number!\n");
}