[英]How to use fscanf() in C to recognize patterns that are recognized as strings?
我想使用fscanf識別以下模式:
Product|10|Meter
一種產品,其數量和米。
使用fscanf()
作為:
fscanf(file, "%s|%d|%s");
我遇到的問題是字符串正在拾取所有內容,而其他變量沒有收到任何值。
這是我的代碼:
while ((fscanf(arqProdTemp, "%s|%d|%s", insumo, qtdInsumos, unidade)) != EOF) {
printf("%s - %d %s", insumo, qtdInsumos, unidade);
}
當我使用printf()
函數時, insumo
的結果就是整個字符串!
如評論中所建議,您可以
fscanf(arqProdTemp, "%[^|]|%d|%s", insumo, &qtdInsumos, unidade);
請注意,如果qtdInsumos
是一個整數變量,則需要使用&qtdInsumos
將其地址傳遞給fscanf()
。 不是它的價值。
insumo
和unidade
是用於存儲字符串的字符數組。 確保數組足夠大以存儲字符串並使用寬度說明符,例如
fscanf(arqProdTemp, "%14[^|]|%d|14%s", insumo, &qtdInsumos, unidade);
其中15是兩個數組的大小。 根據您的需要進行更改。
另外,檢查fscanf()
的返回值以查看是否一切順利。 fscanf()
返回成功分配的數量,在這種情況下,必須為3。
if( fscanf(arqProdTemp, "%[^|]|%d|%s", insumo, &qtdInsumos, unidade) != 3 )
{
//Something went wrong
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.