我需要創建一個程式來逐行讀取檔案,并在每行中掃描一些資料。例如在一行中:
# 2 (x1,y1)(x2,y2)
我需要 x1,y1 和 x2,y2 我的代碼是
char firstCharacter;
char line[100];
scanf("%c",&firstCharacter);
while ((fgets(line, sizeof line, stdin) != NULL) && (line[0] != '\n')){
if(firstCharacter == '#'){
int nu_deadend;
sscanf(line,"%d",&nu_deadend);
for (int i = 0; i < nu_deadend; i ) {
int x,y;
sscanf(line,"(%d,%d)",&x,&y);
printf("x: %d y: %d\n",x,y);
}
}
}
return 0;
但從輸入:
# 2 (2,3)(3,4)
它輸出:
x:0 y:0
x:0 y:0
預期輸出:
x:2 y:3
x:3 y:4
我究竟做錯了什么?
uj5u.com熱心網友回復:
從我的最高評論...
與scanf從中斷處繼續的不同,sscanf將從給定的緩沖區開始。因此,您可能需要使用 (eg)char *cp = line;然后使用并前進cp以指向下一個標記。
sscanf不適合這個,因為它回傳一個計數而不是消耗的位元組數。
最好使用fgets, cp, 和strtok并傳遞strtokto的回傳值sscanf
此外,您永遠不會重置firstCharacter第二行(即我認為每一行都以 開頭#)
這是一個重構版本。注釋為:
#include <stdio.h>
#include <string.h>
#ifdef DEBUG
#define dbgprt(_fmt...) printf(_fmt)
#else
#define dbgprt(_fmt...) do { } while (0)
#endif
int
main(void)
{
char *tok;
char line[100];
// FORMAT:
// # <count> (x,y)(x,y)...
while (fgets(line, sizeof line, stdin) != NULL) {
dbgprt("LINE: %s",line);
// get first token
tok = strtok(line," \n");
if (tok == NULL)
break;
// this must be "#"
if (*tok != '#')
continue;
// get the count
int nu_deadend;
tok = strtok(NULL," \n");
sscanf(tok, "%d", &nu_deadend);
dbgprt("NUM: %d\n",nu_deadend);
// get "(x,y)(x,y)(x,y)"
tok = strtok(NULL," \n");
for (int i = 0; i < nu_deadend; i ) {
int x, y;
dbgprt("TOK: '%s'\n",tok);
sscanf(tok, "(%d,%d)", &x, &y);
printf("x: %d y: %d\n", x, y);
// advance past the end of the current (x,y)
tok = strchr(tok,')');
if (tok == NULL)
break;
tok;
}
}
return 0;
}
這是我使用的測驗輸入:
# 2 (2,3)(3,4)
# 3 (1,7)(9,2)(8,3)
這是除錯輸出:
LINE: # 2 (2,3)(3,4)
NUM: 2
TOK: '(2,3)(3,4)'
x: 2 y: 3
TOK: '(3,4)'
x: 3 y: 4
LINE: # 3 (1,7)(9,2)(8,3)
NUM: 3
TOK: '(1,7)(9,2)(8,3)'
x: 1 y: 7
TOK: '(9,2)(8,3)'
x: 9 y: 2
TOK: '(8,3)'
x: 8 y: 3
而且,這是干凈的輸出:
x: 2 y: 3
x: 3 y: 4
x: 1 y: 7
x: 9 y: 2
x: 8 y: 3
uj5u.com熱心網友回復:
您正在從輸入中讀取“#”。輸入中剩下的(包括初始的“2”)被讀入緩沖區。
與輸入流相反,line您使用的字串在 之后仍然包含已經成功掃描的初始“2” sscanf(line,"%d",&nu_deadend);,而不是在成功掃描后丟失它。
因此,您嘗試掃描“(...)”時需要考慮“2”。
例如喜歡
sscanf(line,"%*d (%d,%d)",&x,&y);
為了第一 ”()”。
第二個要么需要更精細的忽略,要么需要在適當的索引處開始掃描字串內相關的“(”。
由于您需要回圈,因此精細的忽略無濟于事。您必須首先搜索右鍵“(”,然后進行掃描。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388744.html
上一篇:如何使用R更改字串中文本之前的值
