[英]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.