gpt4 book ai didi

c - 如何在 C 中扫描初始空格

转载 作者:太空宇宙 更新时间:2023-11-04 01:23:43 24 4
gpt4 key购买 nike

我有一个典型的问题,不是如何使用 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 个 空格 然后最后是 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("%s\n",ans[i]);
}

scanf("%d",&i);

return 0;
}

最佳答案

OP 代码应该按发布的方式工作。

OP 评论真正的代码正在使用 scanf("%[^\n]",a); 这充分解释了问题:格式中的空间占用了前导空白。

要解决 scanf() 的其他问题,请参阅下文。


fgets() 是正确的工具。

然而,如果 OP 坚持 scanf()

how can I scan spaces using scanf but how to scan the initial spaces entered in a string?

char buf[100];

// Scan up to 99 non\n characters and form a string in `buf`
switch (scanf("%99[^\n]", buf)) {
case 0: buf[0] = '\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] = '\0'; break; // stdin is closed.
}
fgetc(stdin); // throw away the \n still in stdin.

关于c - 如何在 C 中扫描初始空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35753194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com