如何使用scanf从用户获取没有空格的字符串?

时间:2018-11-03 19:19:27

标签: c scanf

这是一个C代码,用于从用户那里获取括号类型为'()'和'<>'和'{}'和'[]'的字符串。该字符串的长度为n,它是用户输入的内容。

int main()
{
  long int n;
  int i;
  scanf("%lld", &n);
  char array[n];
  for(i=0; i<n ; i++)
  {
     scanf("%s", &array[i]);
  }
 }

问题是我想从用户那里获取字符串之间没有任何空格。但是,此代码适用于每个字符之间有空格的输入,并给出正确的结果。

例如,如果我输入{((),该程序将无法运行。但是如果我输入{ ( ( ),程序将显示正确的结果。 我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

更改:

scanf("%s", &array[i]);

对此:

scanf(" %c", &array[i]);

因为您尝试执行的操作是逐字符读取字符串。

请注意%c之前的空格,它将占用从您输入n开始到标准输入缓冲区的尾随换行符。

我曾写过关于scanf() here读取字符时的注意事项。

现在,即使您使用{((){ ( ( )作为输入,也将是相同的,因为scanf()将忽略空格。

但是,如果希望标准函数使用字符串,则应该 null终止,这是您几乎肯定想要的。例如,如果要使用printf("%s", array);,则必须终止array空值。

一种方法,假设用户将正确输入(在理想环境中),则可以执行以下操作:

#include <stdio.h>
int main()
{
  long int n;
  int i;
  scanf("%ld", &n);

  // create an extra cell to store the null terminating character
  char array[n + 1];

  // read the 'n' characters of the user
  for(i=0; i<n ; i++)
  {
     scanf(" %c", &array[i]);
  }

  // null terminate the string
  array[n] = '\0';

  // now all standard functions can be used by your string
  printf("%s\n", array);

  return 0;
 }

PS:scanf("%lld", &n);-> scanf("%ld", &n);。使用编译器的警告!它将告诉您有关..

答案 1 :(得分:0)

如果要确保用户在每个“有效”字符之间键入至少1个空格字符,则可以在循环中等待,直到用户添加空格字符为止。


    char c;
    for (i = 0; i < n; i++)
    {
        c = '\0';
        while (c != ' ')        // wait for the user to type a space character
        {
            scanf ("%s", &c);
        }
        while (c == ' ')        // wait for the user to type something else
        {
            scanf ("%s", &c);
        }
        array[i] = c;
    }

相关问题