使用gcc编译器为gets()函数建议一个替代方法

ama*_*hth 1 c string gcc

尝试在我的程序的字符串数组中输入多个字符串,用于:

scanf("%80[^\r\n]", strings[i]);

fgets(string[i], MAXLEN, stdin);

还使用了自定义功能:

int getString(char s[]) {

    char ch;
    int i=0;

    while( (ch = getchar()) != '\n'   &&   ch != EOF ) {
        s[i] = ch;
        ++i;
    }

    s[i] = '\0';

    fflush(stdin);

    return i;
}
Run Code Online (Sandbox Code Playgroud)

但无法输入多个字符串,每个字符串包含空格

函数gets()过去对我来说比较早,但由于它已被弃用,因此无法找到替代方案

这是使用它的地方:

int getString(char s[]) {

char ch;
int i=0;

while( (ch = getchar()) != '\n'   &&   ch != EOF ) {
    s[i] = ch;
    ++i;
}

s[i] = '\0';

fflush(stdin);

return i;
}


struct vechileData
{
char vechileType[MAXLEN];
int begin_month;
int end_month;
    double price;
} data[5];


int main(int argc, char const *argv[])
{
printf("Input Vechile data: \n");

int i=0;
while(i < 5) {
    printf("Input vechile Type : \n");
    fgets(data[i].vechileType, MAXLEN, stdin);

    printf("Input begin month : \n");
    scanf("%d", &data[i].begin_month);

    printf("Input end monhth : \n");
    scanf("%d", &data[i].end_month);

    printf("Input price : \n");
    scanf("%lf", &data[i].price);

    ++i;
}

printf("Input Vechile Type to display information about the vechile : \n");
char vech[MAXLEN];
fgets(vech, MAXLEN, stdin);

i=0;
while(i < 5) {
    if (strcmp(vech,data[i].vechileType) == 0)
    {
        printf("vechileType: %s\n", data[i].vechileType);
        printf("Begin month: %d\n", data[i].begin_month);
        printf("End month: %d\n", data[i].end_month);
        printf("Price : %lf\n", data[i].price);
    }
    ++i;        
}

return 0;
}
Run Code Online (Sandbox Code Playgroud)

它在运行时跳过字符串语句的下一个输入,"似乎"

chu*_*ica 5

你的问题确实不是gets()问题.

没有scanf("%d", ...)scanf("%lf", ...)消费'\n'后的数字,从而有助于您的问题.这是接下来要读stdin的内容'\n'.因此,当读取下一个车型时,它会挥之不去'\n'.你的第二种车型最终会出现"\n".

使用fgets(data[i].vechileType, MAXLEN, stdin);把一个'\n'data[i].vechileType.你可能不想要这个.你以前用过的gets()消费,但没有把'\n'它归还.

scanf()由于这些微妙的问题,我很久以前就放弃了用户输入.建议将输入与解析,使用fgets()然后分开sscanf().例:

char number[80];
if (fgets(number, sizeof(number), stdin)) {
  sscanf(number, "%d", &x)
Run Code Online (Sandbox Code Playgroud)

您对gets()替换的实施方式不同如下

1)它不返回s(或NULL或错误/ eof).
2)它没有在eof上设置eof指示符.3)应该getchar()返回a '\0',你的while循环错误地继续.


建议如果必须更换gets(),请通过fgets().

#define My_gets_N (1024 /* Some BA number */)

char *My_gets(char * str) {
  char buffer[My_gets_N];
  char *retval = fgets(buffer, sizeof(My_gets_N), stdin);
  if (retval) {
    int l = strlen(buffer);
    /* fgets() saves '\n', but gets() does not */
    if ((l > 0) && (buffer[l-1] == '\n')) {
      l--;
    }
    memcpy(str, buffer, l);
    str[l] = '\0';
    return str;
  }
  else {
    return 0;
  }
}
Run Code Online (Sandbox Code Playgroud)

如果替换解决方案需要处理字符串长度>固定My_gets_N,则需要其他编码.