-1

我需要创建一个程序来读取字符串“A = B”并在变量数组中搜索 B。如果它没有找到 B,那么它会询问它的值并将其放入另一个数组中。好吧,我不知道这个想法是否清楚,但这里有一个例子:

  while(1){
  printf("Get string\n");
  gets(L);


  if(L[0]=='\0') break;

  if(L[2] == '1') {
          printf("Value of 1: ");
          scanf(" %lf", &m);

          }

          }
  printf("\nbreak");

我需要当我们输入回车时这个程序停止,所以我使用了 if(L[0]=='\0') break; 为了它。

我的问题是:每次我问B的值时,我的程序都会读取一个“鬼串”L,是的,它不让我输入L的值,程序就停止了。它几乎是双重读取字符串,但由于条件 L[0] != '\0' 而中断。我究竟做错了什么?如果我们删除这个条件,那么程序会打印 2 次“获取字符串”,而不要求我输入字符串 2 次。

4

3 回答 3

2

Don't (ever) use gets(). It's not good.

Use fgets() instead, noting that it stores the linefeed. Use some higher-level function (like sscanf()) to parse out the input. Likewise, use another fgets() + sscanf() combo to do the value reading.

于 2013-09-11T12:32:04.707 回答
0

You're doing it wrong, since you never check for errors (including end of file). That's why you're reading twice.

Instead do e.g.

while ((fgets(L, sizeof(L), stdin) != NULL)
{
    /* ... */
}
于 2013-09-11T12:33:39.203 回答
0

你 scanf 不消耗行终止符,只是在它之前输入的内容。因此,gets() 会看到行终止符,并返回一个空字符串。

于 2013-09-11T12:36:22.180 回答