【问题标题】:Why he's skippind the reading of the second scanf为什么他跳过第二次 scanf 的阅读
【发布时间】:2021-07-19 15:52:51
【问题描述】:

所以,我有下面的代码,我需要将 str2 中的前“N”个字符连接到 str1。但是IDK为什么当我输入str1时他会自动跳转到读取N并跳过str2读取,str1和str2读取完全一样。

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

int main(void) {
  char str1[50], str2[25];
  int n, tam;

  printf("Type the first string: ");
  scanf("%[^\n]s", str1);
  printf("Type the second string: ");
  scanf("%[^\n]s", str2);
  printf("Type N: ");
  scanf("%d", &n);
  tam = strlen(str1);

  for(int i=0; i<n; i++){
    tam++;
    str1[tam] = str2[i];
  }

  printf("Final string: %s\n", str1);

  return 0;
}

heres what happening

【问题讨论】:

  • 这能回答你的问题吗? Scanf skips every other while loop in C
  • 建议:不要将%[...] 表单与scanf 一起使用。我知道为什么有人告诉你使用它,但从长远来看这是一个坏主意。 (从长远来看,你想完全不用scanf 来做任何事情。)如果你曾经使用%s%s%d 来读取你的第一个字符串和你的第二个字符串以及你的号码,它会工作得很好。

标签: c


【解决方案1】:

改变

  printf("Type the first string: ");
  scanf("%[^\n]s", str1);
  printf("Type the second string: ");
  scanf("%[^\n]s", str2);

  printf("Type the first string: ");
  scanf("%[^\n]s", str1);
  getchar();
  printf("Type the second string: ");
  scanf("%[^\n]s", str2);

问题是第二个scanf在第一个scanf之后从enter键获取输入,所以需要重置缓冲区。

【讨论】:

  • 或 scanf(" %[^\n]s", str2);没有 getchar();
  • % 之前的空格设计 用于过滤任意数量的空格(或无空格),但getchar() 必须准确读取一个字符,无论它是单个不需要的空格或需要的数据(无空格)。这是一个可怜的组合。 %[^\n]s 中的 s 是典型的新手错误:%[] 是与 %s 不同的格式,具有不同的行为。
【解决方案2】:

您需要使用按回车键生成的换行符 (\n)。

应该通过添加一个scanf来解决。

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

int main(void) {
  char str1[50], str2[25];
  int n, tam;

  printf("Type the first string: ");
  scanf("%[^\n]s", str1);
  scanf("%*c");
  printf("Type the second string: ");
  scanf("%[^\n]s", str2);
  scanf("%*c");
  printf("Type N: ");
  scanf("%d", &n);
  tam = strlen(str1);

  for(int i=0; i<n; i++){
    tam++;
    str1[tam] = str2[i];
  }

  printf("Final string: %s\n", str1);

  return 0;
}

%*c 将使用换行符 \n 而不会将其存储在任何地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2012-05-21
    • 2014-08-06
    • 2011-08-30
    • 2017-05-02
    • 2021-11-07
    相关资源
    最近更新 更多