你怎么读txt文件制表符分隔字符串,并把它们放到变量? [英] How do you read tab delimited strings from a txt file and put them into variables?

查看:225
本文介绍了你怎么读txt文件制表符分隔字符串,并把它们放到变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我想要阅读和填写变量的文件。该文件包含这样的:

I have a file that I'm trying to read and fill variables with. The file consists of this:

0\ttake a nap\n
1\tstudy heap-based priority queue\n
101\treview trees for Midterm 2\n
3\tdo assignment 7\n

这可能是难以阅读,但你可以看到,有开始与一个整数,然后是一个选项卡,在这之后的字符串,然后是一个换行符。我需要整数并将它放入一个变量,检测的标签,并把字符串后面的标签到一个变量,检测换行,取两个变量,创建具有信息的节点,然后在重新开始下一行。之后在网上淘的时间,这是我想出:

This may be hard to read, but you can see that there is an integer to begin with, followed by a tab, a string after that, followed by a newline. I need to take the integer and put that into a variable, detect the tab, and put the string following the tab into a variable, detect the newline, take the two variables and create a node with the information, and then start over again on the next line. After hours of scouring the internet, this is what I've come up with:

char activity[SIZE];
 char position[SIZE];
 char line[100];

  FILE *infile;
  char *inname = "todo.txt";

  int i = 0;


  infile = fopen(inname, "r");
  if (!infile) {
    printf("Couldn't open %s for reading\n");
    return 0;
  }
while(i < 100 && fgets(line, sizeof(line), infile) != NULL){
        sscanf(line, "%s\t%s", position, activity);
        printf("%s\n", position);
        printf("%s\n", activity);
        i++;
    }

在运行上面的txt文件,本次测试code,我得到这个结果:

When running this test code on the txt file above, I get this as a result:

0
take
1
study
101
review
3
do

因此​​,它看起来对我来说,这是正常的得到的第一个数字(作为一个字符串),并把它变成变量,眼看着标签,标签后抓住了第一个序列,并把它变成另一个变量后止步。我该如何改变这种状况?

So, it looks to me like it's getting the first number alright (as a string) and putting it into the variable, seeing the tab, and grabbing the first sequence after the tab and stopping there after putting it into the other variable. How do I rectify this situation?

推荐答案

您可以尝试更改的sscanf

sscanf(line, "%s\t%[^\n]", position, activity);

%S 当它遇到空格符停止。这就是为什么它只是读取的研究的而不是基于堆的研究优先级队列的的。在%[^ \\ n] 告诉它:看,直到换行。另一个问题:你应该测试通过的sscanf 的返回值,以确保它填补了所需数量的对象

The %s specifier stops when it encounters blanks. That's why it only reads study instead of study heap-based priority queue. The %[^\n] tells it: "read until newline". Another issue: you should test the value returned by sscanf to make sure it filled the required number of objects.

您也可以阅读的第一个整数为整数,改变位置 INT ,并使用%d个而不是%S

You could also read the first integer as an integer, changing position to int and using %d instead of %s.

要讲清楚,我是在暗示是:

To make myself clear, what I was suggesting was:

int position;
sscanf(line, "%d\t%[^\n]", &position, activity);

这篇关于你怎么读txt文件制表符分隔字符串,并把它们放到变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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