如果你想從一個文件亂七八糟挑出唯一整數,那麼你實際上需要通過每次用指針來識別每個開始識讀線工作(或開始-
負號碼的符號)轉換每次發現一個整數。你可以用指針和sscanf
來做到這一點,或者你可以用strtol
做到這一點,使用endptr
參數在成功轉換後移動到下一個字符。您也可以使用面向字符的輸入(例如getchar
或fgetc
)手動執行數字識別和轉換(如果您喜歡)。
鑑於您開始使用fgets
和sscanf
方法,下面繼續。無論您使用的是sscanf
還是strtol
,整個密鑰都是在每個找到的整數之後,將下一次讀取的開始時間推進到字符,例如,
#include <stdio.h>
#include <stdlib.h>
#define MAXC 256
int main (int argc, char **argv) {
char buf[MAXC] = ""; /* buffer to hold MAXC chars at a time */
int nval = 0; /* total number of integers found */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
}
while (fgets (buf, MAXC, fp)) {
char *p = buf; /* pointer to line */
int val, /* int val parsed */
nchars = 0; /* number of chars read */
/* while chars remain in buf and a valid conversion to int takes place
* output the integer found and update p to point to the start of the
* next digit.
*/
while (*p) {
if (sscanf (p, "%d%n", &val, &nchars) == 1) {
printf (" %d", val);
if (++nval % 10 == 0) /* output 10 int per line */
putchar ('\n');
}
p += nchars; /* move p nchars forward in buf */
/* find next number in buf */
for (; *p; p++) {
if (*p >= '0' && *p <= '9') /* positive value */
break;
if (*p == '-' && *(p+1) >= '0' && *(p+1) <= '9') /* negative */
break;
}
}
}
printf ("\n %d integers found.\n", nval);
if (fp != stdin) fclose (fp); /* close file if not stdin */
return 0;
}
示例輸入
以下兩個輸入文件演示僅挑選出的整數混合輸入的。您的文件:
$ cat dat/blah.txt
8 blah blah
10 blah blah
2 blah blah
3 blah blah
一個非常混亂的文件
$ cat ../dat/10intmess.txt
8572,;a -2213,;--a 6434,;
a- 16330,;a
- The Quick
Brown%3034 Fox
12346Jumps Over
A
4855,;*;Lazy 16985/,;a
Dog.
11250
1495
示例使用/輸出
你的情況:
$ ./bin/fgets_sscanf_int_any_ex < dat/blah.txt
8 10 2 3
4 integers found.
隨着真的很亂文件:
$ ./bin/fgets_sscanf_int_any_ex <dat/10intmess.txt
8572 -2213 6434 16330 3034 12346 4855 16985 11250 1495
10 integers found.
看看,讓我知道你是否有任何問題。
停止。使用'fgets',然後用'strtol'解析 –
另外,請參閱http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong –
數字總是在開頭一條線?是否總是有一個數字?一行上能有多少數字?數字可以被字母或標點符號包圍嗎?你需要擔心跡象嗎? –