如何扫描 C 语言中的初始空格



我有一个典型的问题,不是如何使用scanf扫描空格,而是如何扫描字符串中输入的初始空格

这是我所做的:

    #include <stdio.h>
    #include <string.h>
    int main()
    {
       int n;
       char a[10];
       scanf("%d",&n);
       scanf(" %[^n]",a);
       printf("%d",strlen(a));
       return 0;
     }

当我使用以下输入运行程序时:

   aa bb//note there are two spaces before initial a

输出是6但有 8 个字符,即 2 spaces后跟 2 a,后跟 2 spaces,最后是 2 b

我尝试了自己的功能..但是唉!长度是6.这是我的函数:

int len(char a[101])
{
    int i;
    for(i=0;a[i];i++);
    return i;
}

我认为最初的 2 个空格被忽略了......或者我可能是错的。如果有人能解释为什么字符串的长度6以及如何使其8或接受我上面提到的所有8字符,那就太好了。

编辑:这是我的实际代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int i,N,j,k;
    char **ans,s[101];
    scanf("%d",&N);
    ans=(char **)calloc(N,sizeof(char*));
    for(j=0,i=0;i<N;i++)
    {
        scanf(" %[^n]",s);
        printf("%d",strlen(s));
        ans[i]=(char*)calloc(strlen(s),sizeof(char));
        for(k=0,j=((strlen(s)/2)-1);j>=0;j--,k++)
        {
            ans[i][k]=s[j];
        }
        for(j=strlen(s)-1;j>=strlen(s)/2;k++,j--)
        {
            ans[i][k]=s[j];
        }
    }
    for(i=0;i<N;i++)
    {
        printf("%sn",ans[i]);
    }
    scanf("%d",&i);
    return 0;
}

OP 代码应该按照发布的那样工作。

OP 注释 true 代码正在使用 scanf(" %[^n]",a); 这充分解释了这个问题:格式中的空格正在消耗前导空格。

要解决与scanf()有关的其他问题,请参阅以下内容。


fgets()是正确的工具。

然而,如果OP坚持scanf()

如何使用 scanf 扫描空格,但如何扫描字符串中输入的初始空格?

char buf[100];
// Scan up to 99 nonn characters and form a string in `buf`
switch (scanf("%99[^n]", buf)) {
  case 0: buf[0] = ''; break;   // line begins with `'n`
  //  May want to check if strlen(buf)==99 to detect a long line
  case 1: break;                  // Success.
  case EOF: buf[0] = ''; break; // stdin is closed.
}
fgetc(stdin); // throw away the n still in stdin.

我认为的问题是您需要从指针到数组而不是数组本身获取长度。试试这个,这段代码对我有用。

int ArrayLength(char* stringArray) 
{
   return strlen(stringArray);
}

最新更新