[英]C - fscanf scanset not working after linebreak
int i = 0;
while (fscanf(fi, "%[^,],%[^,],%[^,],%[^,],%[^\n]\n", buf.first,
buf.second,
buf.third,
buf.fourth,
buf.fifth) == 5)
{
if (i == 0)
{
ptr->pid = atol(buf.first);
ptr->name = buf.second;
ptr->ram = atoi(buf.third);
ptr->size = atof(buf.fourth);
ptr->os = buf.fifth;
}
i++;
}
printf("%li %s %d %.2f %s\n", ptr->pid, ptr->name, ptr->ram, ptr->size, ptr->os);//test
無論如何,掃描都出了問題,我用\\ n替換了輸入文件\\ r \\ ns,但是它仍然掃描錯誤的項目。 當我在輸入文件中每行的末尾添加逗號-s並在掃描中將“ \\ n”替換為“,\\ n”時,它會正確顯示第一個元素,但不會掃描其他元素。
找出問題的人都應該得到cookie。
掃描沒有問題。 問題在於您使用char *
的in循環的方式。
ptr->pid = atol(buf.first);
ptr->name = buf.second; // <-------1
ptr->ram = atoi(buf.third);
ptr->size = atof(buf.fourth);
ptr->os = buf.fifth; // <-------2
在輸出中,您看到整數或浮點數沒有變化,與第一個條目相同,但字符串已更改(作為讀取的最后一個值輸出) 。
因為正如您指向指針而不是復制一樣,如注釋1和2所示。 因此,它所指向的值也將更改為輸出 。
因此,使用strcpy
復制字符串而不是指向它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.