我正在尝试制作一个以安全方式返回字符串的简单函数,我想知道这段代码有什么问题。
我决定使用 read 因为 scanf 和 fgets 都给 e 带来了麻烦,
具体来说,如果我明显溢出缓冲区,即使进行了长度检查,scanf 也会给我中止陷阱 6,
当 fgets 接受输入时,如果我插入的字符串太长,则返回错误消息,但无论如何都会预先转换字符串,不允许我重新输入另一个字符串。
这是代码:
string get_string(const string prompt)
{
char temp[30];
int size,count;
printf("%s",prompt);
do
{
count=read(0,temp,29);
temp[count]='\0';
size=strlen(temp);
if(size>24)
{
printf("\x1B[31mError\x1B[0m: too long.\n%s",prompt);
}
printf("size :%i\n",size);
}
while(size>24);
stripc(temp,'\n'); //removes new line
string word=malloc((size)*sizeof(char));
strcpy(word,temp);
return word;
}
现在读取它给了我同样的错误,我从标准输入读取了总共 30 个字节,
然后我在计数器的末尾添加空字符,但如果长度超过这是输出:
ppppppppppppppppppppppppppppp
Error: too long.
size :30
size :2
p
知道问题出在哪里吗?
还有其他方法可以实现我的需求吗?
编辑:问题不是超出范围,
奇怪的是,一旦我写了超过 24 个字符,
应该读取输入的函数(read、scanf、fgets 或其他),
不再激活,这就是为什么尺寸:连续出现两次,
由于某种原因跳过了输入插入,我想了解原因。
我纠正了一些错误。
最佳答案
如果在第一个输入中没有找到换行符,则调用 fgets 直到找到换行符以清理输入流,然后继续外部 while 循环。
string get_string(const string prompt)
{
char temp[26] = "";//24 + newline + '\0'
int size,count;
while ( 1)
{
printf ( "%s",prompt);
if ( fgets ( temp, sizeof temp, stdin)) {
if ( !strchr ( temp, '\n')) {//no newline
printf("\x1B[31mError\x1B[0m: too long.\n%s",prompt);
size = strlen ( temp);
do {
fgets ( temp, sizeof temp, stdin);//read more and discard
size += strlen ( temp);
} while (!strchr ( temp, '\n'));//loop until newline found
printf("size :%i\n",size);
continue;//re prompt
}
break;
}
else {
fprintf ( stderr, "fgets problem\n");
return NULL;
}
}
temp[strcspn ( temp,"\n")] = '\0';//remove newline
string word = malloc(strlen ( temp) + 1);
strcpy ( word, temp);
return word;
}
关于c - 在 C 中创建获取字符串函数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48282630/