[英]Use scanf to scan a word only but with space at the front
是否可以僅在C語言中掃描帶有空格+一個單詞的文本?
這是示例文本:
"Oh my god!"
這是函數:
...declarations...malloc...etc.
for (int i = 0; ; i++)
{
some_scanf_func(s, "%some format", input);
c = getchar();
if (c == EOF)
break;
else
ungetc(c, stdin);
}
這樣我的輸入是:
"Oh" when i = 0;
" my" when i = 1;
" god!" when i = 2;
空格位於單詞的開頭。 打孔算作有效字符。
謝謝chux的把戲,也謝謝Charlie的回答。
使用"%*s%n"
。
%*s
跳過前導空白,然后掃描非空白文本。 *
表示不說結果。
%n
說要記錄掃描的位置(如果我們到達那里)。
char input[100];
char *p = input;
int count = 0;
if (fgets(input, sizeof input, stdin) == NULL) {
; // handle EOF
}
while (*p) {
int n = 0;
sscanf(p, "%*s%n", &n);
if (n == 0) break;
p = &p[n];
count++;
}
用buffer
隔離單詞
char *previousp;
while (*p) {
int n = 0;
sscanf(p, "%*s%n", &n);
if (n == 0) break;
previousp = p
p = &p[n];
// At this point `previousp` to p is OP desired output.
printf(%.*s\n", p - previousp, previousp);
count++;
}
OP希望使用sscanf()
但按照@Charlie Burns的建議簡單地進入緩沖區很有意義。
const char *p = buffer;
while (*p) {
const char *endp = p;
while (isspace(*endp)) endp++;
while (*endp && !isspace(*endp)) endp++;
// At this point `p` to `endp` is OP desired output.
printf(%.*s\n", endp - p, p);
p = endp;
}
另一種方法是:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int foo(char *s, char **result, int size) {
char *p1 = s;
int count = 0;
while(*p1 && count < size-1) {
char *p2 = p1;
for( ; *p2 && isspace(*p2); p2++);
if(*p2) {
for( ; *p2 && isspace(*p2) == 0; p2++);
result[count++] = strndup(p1, p2 - p1);
}
p1 = p2;
}
result[i] = 0;
return count;
}
int main(void) {
char *result[100];
int n = foo(" Oh my god! ", result, 100);
for(int i = 0; i != n; i++) {
printf("%d '%s'\n", i, result[i]);
free(result[i]);
}
return 0;
}
我想有點丑陋。 但它打印
0 ' Oh'
1 ' my'
2 ' god!'
並使用原始輸入執行正確的操作。
將其讀取為字符串-然后對其進行解析。
在檢測是否存在空格之后,可以使用sscanf()解析與scanf相同的字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.