读取带有C空格的字符串

时间:2016-11-11 16:00:42

标签: c fgets scanf

我正在尝试读取可能包含或不包含空格的字符串。 "你好世界"。通过用户输入的数字选择菜单进行以下操作。这只是我想要做的一个小复制品。

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

int main(void){
  char line[3][80];

  strcpy(line[0],"default line 1\n");
  strcpy(line[1],"default line 2\n");
  strcpy(line[2],"default line 3\n");

  for(int i = 0; i < 3; i++){
    printf("%s", line[i]);
  }

  int option = 0;
  printf("would you like to replace line 1? (1 for yes)\n");
  scanf("%d",&option);
  if(option==1){
   printf("what would you like to replace the line with?\n");
   fgets(line[0],strlen(line[0]),stdin);
  }

  for(int i = 0; i < 3; i++){
    printf("%s", line[i]);
  }
}

为什么在我输入1更改行之后,它会打印语句询问我想要替换它的内容并自动输入任何内容然后打印字符串,第一个字符串为空?

我也已经尝试用sscanf("%[^\n\t]s", line[0]);阅读这条线而没有任何运气。有什么想法吗?

3 个答案:

答案 0 :(得分:10)

这是因为

scanf("%d",&option);

\n字符留在stdin中,并在第一次调用fgets()时使用。 这就是为什么最好完全避免C中的scanf()

你可以用以下方法修复它:

  scanf("%d",&option);
  getchar(); /* consume the newline */

但我建议您使用fgets()来阅读option,然后您可以使用enter image description here将其转换为整数。

请注意,此声明可能不是您的意图(这限制了您可以阅读line[0]的内容)。

   fgets(line[0],strlen(line[0]),stdin);

您可能打算使用:

   fgets(line[0],sizeof line[0],stdin);

这样您就可以阅读line[0]的实际尺寸。

请同时阅读C Faq条目:strtol()

答案 1 :(得分:3)

使用fgets()通常看起来不像使用scanf()那样容易出错,但如果用户输入的字符串与指定的最大字符数一样长或更长,那么任何额外的字符都会增加包含换行符并保留在输入流中。出于这个原因,我通常编写自己的gets()版本来获取用户的输入字符串,如果我想要数字输入,我使用strtol()。以下是此类功能的示例:

char * s_gets(char *st, int n)
{
    char *ret;
    int ch;

    ret = fgets(st, n, stdin);
    if (ret) {
        while (*st != '\n' && *st != '\0')
            ++st;
        if (*st)
            *st = '\0';
        else {
            while ((ch = getchar()) != '\n' && ch != EOF)
                continue;           // discard extra characters
        }
    }
    return ret;
}

应用于OP问题,我可能会这样做:

#include <stdlib.h>                // for strtol()

...

char buf[80];
int option = 0;

printf("would you like to replace line 1? (1 for yes)\n");
s_gets(buf, sizeof(buf));
option = strtol(buf, NULL, 10);

if(option==1){
    printf("what would you like to replace the line with?\n");
    s_gets(line[0],sizeof(line[0]));
}

答案 2 :(得分:2)

您的问题是'\n'字符留在stdin并由fgets消费。

我建议您始终使用fgets进行阅读输入,所以

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

int main(void)
{
    char line[3][80];
    char temp[3];

    strcpy(line[0],"default line 1\n");
    strcpy(line[1],"default line 2\n");
    strcpy(line[2],"default line 3\n");

    for(int i = 0; i < 3; i++){
        printf("%s", line[i]);
    }

    int option = 0;
    printf("would you like to replace line 1? (1 for yes)\n");
    fgets(temp,sizeof(temp),stdin);
    option = atoi(temp);

    if(option==1){
        printf("what would you like to replace the line with?\n");
        fgets(line[0],sizeof(line[0]),stdin);
    }

    for(int i = 0; i < 3; i++){
    printf("%s", line[i]);
    }
}
相关问题