[英]Read formatted text input
我有一個txt文件,我想從中輸入數據。 看起來像這樣:
1 33,3434 34,562 ...
2 24,354 55,234 ...
....
由制表符分隔。 每行末尾還有一個選項卡和一個換行符。 我想在鏈接列表數組中讀取以逗號分隔的數字(作為整數)。 結構如下:
struct node
{
int vertex;
int dist;
struct node* next;
};
我嘗試了以下方法:
1. Using fgets and strtok:
fgets(s,300,fp)
while(strtok(...)!=NULL)
最后,這會讀取一個額外的東西(\\ n,\\ r),這會產生問題。
2. Using fscanf:
for(i=1;i<=SIZE;i++)
{
fscanf(f,"%d",&i);//once per iteration
fscanf(f,"%d,%d",&a,&b);//while it returns 2
}
此方法僅讀取一行。 我不知道如何將指針移到下一行。
3. Using fgets and sscanf:
for(i=1;i<=SIZE;i++)
{
fgets(s,300,f);
sscanf(s,"%d",&c);//once in a loop
sscanf(s,"%d,%d",&a,&b)//while it returns 2
}
但是,由於再次調用sscanf,sscanf的指針不會移動。 我無法一口氣讀一行,因為每一行中的元素數量都在變化
第三種方法最接近,請嘗試此修改。 使用"%n"
知道解析在哪里停止。
注意:請查閱有關使用sscanf()
注釋。
for(i=1; i<=SIZE; i++) {
char s[300];
if (fgets(s, sizeof s,f) == NULL) HandleEarlyEOF();
int a,b,c;
char *p = s;
int n;
if (sscanf(p, "%d%n", &c, &n) != 1) HandleMissingIndex();
p += n;
while (sscanf(p, "%d ,%d%n", &a, &b, &n) == 2) {
Use(a,b,c);
p += n;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.