如何读取文件中的行? [英] How to read a line from file?

查看:177
本文介绍了如何读取文件中的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要读一个txt文件,格式化这样的行:


1:(G,2),(F,3)
2:(G,2),(F,3)
3:(F,4),(G 5)
4:(F,4),(G 5)
5:(F,6),(C,w)的
6:(P,F),(G,7)
7:(G 7),(G,7)
W:(C,W),(C,w)的

每个行会养活结构与它的数据(其中的5个数字或字母)。

什么是读取行,得到我想要的字符串?
我目前使用的条件下长期使用序列龟etc ,但似乎丑陋,不是很聪明。

我不能使用数组,因为行的大小可能会如果数字有两个数字各不相同。


解决方案

 的#include<&stdio.h中GT;INT主要(无效)
{
  焦炭BUF [81]; / *支持线最多80个字符* /
  炭份[5] [11]; / *支持最多10个字符中的每个部分* /  而(与fgets(buf中,sizeof的(BUF),标准输入)!= NULL)
  {
    如果(sscanf的(BUF,%10 [^:]:(%10 ^,],%10 [^)]),(%10 ^,],%10 ^)]),
               份[0],份[1],份[2],份[3],份[4])== 5)
    {
      的printf(部分:%S,%S,%S%S%S \\ n,
             份[0],份[1],份[2],份[3],份[4]);
    }
    其他
    {
      的printf(无效的输入:%S,BUF);
    }
  }
  返回0;
}

样运行:

  $ ./test
1:(G,2),(F,3)
2:(G,2),(F,3)
3:(F,4),(G 5)
4:(F,4),(G 5)
5:(F,6),(C,w)的
6:(P,F),(G,7)
7:(G 7),(G,7)
W:(C,W),(C,w)的
部分:1,G,2,F 3
配件:2,G,2,F 3
配件:3,F,4,G,5
部分:4,F,4,G,5
部分:5,F,6,C,W
份:6,P,F,G,7
份:7,G 7,G 7
部位:W,C,W,C,W

如果输入的最后一个值是超过10个字符,它将与任何迹象的错误被截断,如果这是不能接受的,你可以使用%C 转换说明作为第六个参数的最后一个值后,捕捉到下一个字符,并确保它是一个右括号。

I have to read a txt file with lines formated like this:

1: (G, 2), (F, 3)
2: (G, 2), (F, 3)
3: (F, 4), (G, 5)
4: (F, 4), (G, 5)
5: (F, 6), (c, w)
6: (p, f), (G, 7)
7: (G, 7), (G, 7)
w: (c, w), (c, w)

Each line will feed a struct with its data (the 5 numbers or letters in it).
What's the best way to read the line and get the strings I want?
I'm currently using a long sequence of conditions using fgetc but that seems ugly and not very smart.
I can't use arrays because the lines may vary in size if the numbers have two digits.

解决方案

#include <stdio.h>

int main (void)
{
  char buf[81];       /* Support lines up to 80 characters */
  char parts[5][11];  /* Support up to 10 characters in each part */

  while (fgets(buf, sizeof(buf), stdin) != NULL)
  {
    if (sscanf(buf, "%10[^:]: (%10[^,], %10[^)]), (%10[^,], %10[^)])",
               parts[0], parts[1], parts[2], parts[3], parts[4]) == 5)
    {
      printf("parts: %s, %s, %s, %s, %s\n",
             parts[0], parts[1], parts[2], parts[3], parts[4]);
    }
    else
    {
      printf("Invalid input: %s", buf);
    }
  }
  return 0;
}

Sample run:

$ ./test
1: (G, 2), (F, 3)
2: (G, 2), (F, 3)
3: (F, 4), (G, 5)
4: (F, 4), (G, 5)
5: (F, 6), (c, w)
6: (p, f), (G, 7)
7: (G, 7), (G, 7)
w: (c, w), (c, w)
parts: 1, G, 2, F, 3
parts: 2, G, 2, F, 3
parts: 3, F, 4, G, 5
parts: 4, F, 4, G, 5
parts: 5, F, 6, c, w
parts: 6, p, f, G, 7
parts: 7, G, 7, G, 7
parts: w, c, w, c, w

If the last value in the input is more than 10 characters it will be truncated with no indication of error, if this is not acceptable you can use the %c conversion specifier as a sixth argument to capture the next character after the last value and make sure it is a closing parenthesis.

这篇关于如何读取文件中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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