简体   繁体   English

需要放入有限长度的字符串的函数无法正常工作

[英]Function that needs to putt limited length strings doesn't work well

I've got this function i created: 我已经创建了这个函数:

void getWords(int words){
    int remaining, error=0;
    char word[WORD_MAX+1], def[DEF_MAX+1];

    for(remaining = words;remaining > 0;remaining--){
        do{
            printf("Enter definition #%d out of %d:\n",((words+1) - remaining),words);
            gets(word);
            if(strlen(word) > WORD_MAX){
                error = 1;
                printf("\nError! '%s' contains %d characters | Maximum allowed: %d | Please try again...\n\n",word,strlen(word),WORD_MAX);
            }
        }while(error);
    }
}

It does what it should do basically, checks if the string length is at most 'WORD_MAX' characters long and if not asks the user to do it again, My problem is this: 它会执行它应做的基本工作,检查字符串长度是否最多为“ WORD_MAX”个字符,如果不要求用户再次执行此操作,我的问题是:

when i tested it with WORD_MAX of 3 and tried to write a 6 characters long string it works perfectly, but when i tried to write a really long string, for example 20 chars long, it wrote only some of the word, with some weird ascii smiley on the end, and the 'remaining' variable which contains the number of words i ask the function to input get some garbage value and it ruins the whole program, why does it do that? 当我使用WORD_MAX为3进行测试并尝试编写一个6个字符长的字符串时,它可以正常工作,但是当我尝试编写一个非常长的字符串(例如20个字符长)时,它只写了一些单词,并带有一些奇怪的ascii最后是笑脸,而“剩余”变量包含我要求函数输入的单词数,它会得到一些垃圾值,并且破坏了整个程序,为什么这样做呢?

Thank you! 谢谢!

As you've noticed, there is no way to avoid buffer overflow with gets . 您已经注意到,没有办法避免使用gets缓冲区溢出。 As an alternative, you could use fgets 或者,您可以使用fgets

fgets(word, WORD_MAX+1, stdin);

From its man page 从其手册页

char *fgets(char *s, int size, FILE *stream); char * fgets(char * s,int size,FILE * stream);
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. fgets()最多从流中读取小于大小的字符,并将它们存储到s所指向的缓冲区中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM