[英]How to scan initial spaces in 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;
}
我认为最初的两个空格被忽略了...否则我可能是错的。 有人可以解释为什么字符串的长度是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()
如何使用scanf扫描空格,但如何扫描字符串中输入的初始空格?
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.
我相信的问题是,您需要从指针到数组的长度而不是数组本身的长度。 试试这个,这段代码对我有用。
int ArrayLength(char* stringArray)
{
return strlen(stringArray);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.