更新时间:2023-10-28 14:48:16
正如我在评论中提到的,scanf
函数系列 具有简单的模式匹配,可用于读取您的输入:
char text[32];整数值;while (fscanf(file, "(%32[^,], %d)", text, &value) == 2){printf("得到 (%s, %d)\n", 文本, 值);}
使用的scanf
格式说明:
"("
匹配左括号%32[^,]"
匹配(最多 32 个)字符除了逗号","
匹配逗号%d"
匹配整数值")"
匹配右括号I have a text file that contains data that contains key-value pairs
(Ann, 67) (Jhon, 78) (Mason, 89)
(Simon, 34) (Ruko, 23)
Each item is separated by space and there is a space after comma
I want to read each element and print those items one by one
(Ann, 67)
(Jhon, 78)
(Mason, 89)
(Simon, 34)
(Ruko, 23)
I tried using the following code:
while (fscanf(file, "%s", value) == 1) {
printf(value);
}
but have not succeded - the code separated each value with a comma giving me the following output:
(Ann,
67)
(Jhon,
78)
(Mason,
89)
How can I do that?
As I mentioned in my comment, the scanf
family of functions have simple pattern matching which could be used to read your input:
char text[32];
int value;
while (fscanf(file, " (%32[^,], %d)", text, &value) == 2)
{
printf("Got (%s, %d)\n", text, value);
}
Explanation of the scanf
format used:
" "
matches any leading white-space"("
matches the opening parenthesis"%32[^,]"
matches (at most 32) characters except the comma","
matches the comma"%d"
matches the integer value")"
matches the closing parenthesis