读取.txt文件并将单词/整数作为字符串

时间:2016-10-15 15:14:16

标签: c file

我有一个.txt文件:

scala> object Abc {
    def test(a: Int): Int = a match { case 1  => 1}
  }
defined object Abc

scala> object Main extends App {
    println("Hello world")
    println(Abc.test(1))
  }
defined object Main

scala< Main.main(Array(""))
Hello world
1

编辑: 新问题。我尝试使用fgets一次使用while函数获取1行,然后使用sscanf遍历该行并将每个单词/整数变为自己的字符串。所以从理论上讲,第一个term_in应该是apple然后是123然后是12等等。好吧现在它编译但它不起作用。什么都没有打印出来。

apple 123 12 1 7 3 222
danger 1234 11 223 44 87 65
what 2322 6567 54 
its 9128 88 66 12 12

1 个答案:

答案 0 :(得分:0)

你越来越近了。这是一个小修改 - 一个有效的MCVE(Minimal, Complete, Verifiable Example):

#include <stdio.h>

int main(void)
{
    int offset;
    char line[1000];
    FILE *fp = stdin;   // Important but simple change
    char term_in[1000];

    while (fgets(line, sizeof(line), fp) != NULL) {
        char *data = line;
        while (sscanf(data, "%s%n", term_in, &offset) == 1) { // Changes
            data += offset;
            printf("[%s]\n", term_in);  // Trivial change
        }
    }

    return 0;
}

这是一个示例运行(它被称为rl59.c并编译为rl59):

$  rl59 <<< 'Once upon a time, there was a country that held nice, civilized presidential elections.'
[Once]
[upon]
[a]
[time,]
[there]
[was]
[a]
[country]
[that]
[held]
[nice,]
[civilized]
[presidential]
[elections.]
$

并给出一个多行输入文件:

So she went into the garden
to cut a cabbage-leaf
to make an apple-pie
and at the same time
a great she-bear coming down the street
pops its head into the shop
What no soap
So he died
and she very imprudently married the Barber
and there were present
the Picninnies
and the Joblillies
and the Garyulies
and the great Panjandrum himself
with the little round button at top
and they all fell to playing the game of catch-as-catch-can
till the gunpowder ran out at the heels of their boots

输出结果为:

[So]
[she]
[went]
[into]
[the]
[garden]
[to]
[cut]
[a]
[cabbage-leaf]
[to]
[make]
[an]
[apple-pie]
[and]
[at]
[the]
[same]
[time]
[a]
[great]
[she-bear]
[coming]
[down]
[the]
[street]
[pops]
[its]
[head]
[into]
[the]
[shop]
[What]
[no]
[soap]
[So]
[he]
[died]
[and]
[she]
[very]
[imprudently]
[married]
[the]
[Barber]
[and]
[there]
[were]
[present]
[the]
[Picninnies]
[and]
[the]
[Joblillies]
[and]
[the]
[Garyulies]
[and]
[the]
[great]
[Panjandrum]
[himself]
[with]
[the]
[little]
[round]
[button]
[at]
[top]
[and]
[they]
[all]
[fell]
[to]
[playing]
[the]
[game]
[of]
[catch-as-catch-can]
[till]
[the]
[gunpowder]
[ran]
[out]
[at]
[the]
[heels]
[of]
[their]
[boots]