[英]How to scan initial spaces in C
I have a typical question it's not that how can I scan spaces using scanf but how to scan the initial spaces entered in a string 我有一个典型的问题,不是我如何使用scanf扫描空格,而是如何扫描字符串中输入的初始空格
This is what I've done: 这是我所做的:
#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;
}
and when I run the program with following input: 当我使用以下输入运行程序时:
aa bb//note there are two spaces before initial a
and the output is 6
but there are 8 characters ie, 2 spaces
followed by 2 a
's followed by 2 spaces
and then lastly 2 b
's 输出为
6
但有8个字符,即2个spaces
后跟2 a
,然后是2个spaces
,最后是2 b
I eve tried an own function.. but alas! 我前夕尝试了自己的功能..可惜! the length is
6
. 长度是
6
。 Here's my function: 这是我的功能:
int len(char a[101])
{
int i;
for(i=0;a[i];i++);
return i;
}
What I think is that the initial 2 spaces are being ignored...or I might be wrong. 我认为最初的两个空格被忽略了...否则我可能是错的。 It'd be great if someone could explain why the length of string is
6
and how can I make it 8
or accept all the 8
characters I mentioned above. 有人可以解释为什么字符串的长度是
6
,如何使它变成8
或接受我上面提到的所有8
字符,这将是很棒的。
EDIT: this is my actual code 编辑:这是我的实际代码
#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 code should work as posted. OP代码应按发布的方式工作。
OP comments true code is using scanf(" %[^\\n]",a);
OP注释真实代码正在使用
scanf(" %[^\\n]",a);
which fully explains the problem: the space in the format is consuming leading white-space. 这充分说明了问题:格式中的空间正在消耗前导空白。
To address other issues with scanf()
, see following. 要解决
scanf()
其他问题,请参见下文。
fgets()
is the right tool. fgets()
是正确的工具。
Yet if OP insists on scanf()
但是如果OP坚持使用
scanf()
how can I scan spaces using scanf but how to scan the initial spaces entered in a string?
如何使用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.
The issue i believe is that you need to be getting length from a Pointer to the array not the array itself. 我相信的问题是,您需要从指针到数组的长度而不是数组本身的长度。 Try this, this code worked for me.
试试这个,这段代码对我有用。
int ArrayLength(char* stringArray)
{
return strlen(stringArray);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.