为什么在退出do-while循环请求输入C后程序崩溃?

时间:2015-03-03 20:32:07

标签: c string input do-while string-length

我无法正确使用do-while循环来继续询问另一个字符串,如果一个输入长于你想要的。输入一个太大的字符串后,程序要求另一个字符串,但是在我输入一个可接受的字符串之后,程序崩溃而不是正常退出,为什么会这样?这只是大型程序代码的一部分。另外,我对C来说比较新。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STRING_MAX 100

int main()
{
    //Declaration of variables
    char  temp_input[STRING_MAX];

    //Read input
    do
    {
        scanf("%s", temp_input);
    }while(strlen(temp_input)>STRING_MAX);

    return 0;
}

感谢所有帮助人员!

4 个答案:

答案 0 :(得分:1)

代码失败,因为scanf("%s", temp_input);无法防止因填充temp_input导致过多的长输入导致未定义的行为(UB)

fgets()替代方案:

char buf[STRING_MAX];
while (fgets(buf, sizeof buf, stdin) != NULL) {
  // if input does not end with \n, assume additional char for this line.
  if (strchr(buf, '\n') == NULL) {
    int ch;
    // Get extra char and throw away.
    while ((ch = fgetc(stdin)) != '\n' && ch != EOF)
      ; 
  }

  // do something with buf - get rid of potential trailing \n, then print
  buf[strcspn(buf, "\n")] = 0;
  puts(buf);  // this also prints a \n

  // now get next line
}

答案 1 :(得分:1)

根据评论,我认为这是你真正想要的

#include <stdio.h>

#define STRING_MAX 10

int main (void)
{
    char         string[STRING_MAX];
    unsigned int count;
    unsigned int total;
    int          chr;

    do {
        count = 0;
        total = 0;
        while (((chr = getchar()) != EOF) && (chr != '\n'))
        {
            if (count < STRING_MAX - 1)
                string[count++] = chr;
            total += 1;
        }
        string[count] = '\0';
    } while (total > STRING_MAX - 1);
    printf("The input string was:\n\t%s\n", string);
    return 0;
}

答案 2 :(得分:0)

使用getchar()从stdin读取。它一次获取一个char,因此如果string为long则可以中断。也许你想要像

那样闷闷不乐
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STRING_MAX 100

int main()
{
    //Declaration of variables
    char  temp_input[STRING_MAX];
    int ch;  // char just read
    int ins; // insert point

    //Read input
    ins = 0; // start at begining
    for(;;)
    {
        ch = getchar();
        if( ch == 13 ) // return char
        {
            temp_input[ins] = 0; // null terminate string
            break;
        }
        temp_input[ins] = ch;
        ins++; // move up next insert point
        if( ins == STRING_MAX )
        {
            temp_input[STRING_MAX-1] = 0; // null terminate;
            break;  // at end of string
        }
    }

    return 0;
}

答案 3 :(得分:-1)

您导致缓冲区溢出,请勿将scanf用于此目的。