我如何在 C 中读取文本文件并将其打印到屏幕上? [英] How might I read a text file in C and print it to the screen?

查看:90
本文介绍了我如何在 C 中读取文本文件并将其打印到屏幕上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含键值对数据的文本文件

(Ann, 67) (Jhon, 78) (Mason, 89)(西蒙, 34) (Ruko, 23)

每一项用空格隔开,逗号后有一个空格

我想读取每个元素并一个一个打印这些项目

(安,67)(约翰,78 岁)(梅森,89)(西蒙,34 岁)(Ruko, 23)

我尝试使用以下代码:

<预><代码>而(fscanf(文件,%s",值)== 1){打印(值);}

但没有成功 - 代码用逗号分隔每个值,给我以下输出:

(安,67)(约翰,78)(石匠,89)

我该怎么做?

解决方案

正如我在评论中提到的,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

这篇关于我如何在 C 中读取文本文件并将其打印到屏幕上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆