簡體   English   中英

如何在C中使用fscanf()識別被識別為字符串的模式?

[英]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() 不是它的價值。

insumounidade是用於存儲字符串的字符數組。 確保數組足夠大以存儲字符串並使用寬度說明符,例如

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM