且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何在 C 中读取文本文件并将其打印到屏幕上?

更新时间: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