如何从C中的.text FILE打印每三个(或第n个)单词?

时间:2014-08-21 05:46:40

标签: c file

如何从C中的FILE打印每三个(或第n个)单词?

例如,如果这是文件中的内容:

我想打印此txt文件中的每三个字

出局应该是:

以 第三 此

我试图计算单词之间的空格,例如每隔三个空格,打印下一个i字符,但我失败了,因为第一个单词后面没有任何空格。

3 个答案:

答案 0 :(得分:1)

只有2个状态的状态机。

  • 从stdin
  • 读取输入
  • 参数提供模数和想要的单词。
  • 该程序将所有非字母字符视为空格
  • 可能存在一些逐个错误; - )


#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main (int argc, char **argv)
{

int ch;
int state;
unsigned nword, iword, wantword;

if (argc < 2) { exit (EXIT_FAILURE); }

if ( sscanf( argv[1] , "%u", &nword) <1) { exit (EXIT_FAILURE); }
if ( sscanf( argv[2] , "%u", &wantword) <1) { exit (EXIT_FAILURE); }
if ( wantword >= nword) { exit (EXIT_FAILURE); }

for( iword = 0, state = 0; ; ) {
        ch = getc(stdin);
        if (ch == EOF) break;
        switch (state) {
        case 0:
                if (!isalpha(ch)) continue;
                state = 1; iword++;
                break;
        case 1:
                if (isalpha(ch)) break;
                state = 0;
                putc( ' ' , stdout);
                continue;
                }
        if (iword % nword == wantword) putc( ch , stdout);
        }
exit (EXIT_SUCCESS);
}

答案 1 :(得分:0)

试试这段代码!

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="I want to print every third word from this txt file";
  char * pch;
  int count = 0;
  pch = strtok (str," ");
  count ++;
  while (pch != NULL)
  {
    if (count % 3 == 0)    //In place of 3 you can use n
    {
        printf ("%s ",pch);
    }
    pch = strtok (NULL, " ");
    count++;
  }
  printf("\n");
  return 0;
}

<强>输出

to third this

答案 2 :(得分:0)

试试这段代码 -

#include<stdio.h>
#include<string.h>
int main()
{
        FILE *fp;
        char buffer[20],arr[5][20]; // declare a new array for storing the strings
        int count = 0, i = 0,j;
        fp=fopen("abcd","r");
        if(fp == NULL){
                printf("Failed to open the file\n");
                return -1;
        }
        while(fscanf(fp,"%s",buffer)!=EOF){
                count += 1;
                if(count == 3){
                        printf("%s ",buffer);
                        strcpy(arr[i],buffer); // copy every string to array
                        count = 0;
                        i++;
                }
        }
        printf("\n");
        // Here i am doing printing. Instead of this you can access your string
        for(j=0;j<i;j++)  
        printf("%s\n",arr[j]); // Now you can access it by arr[0], arr[1]... upto i-1.

        return 0;
}

文件内容可能是这种类型 -

   I   want   to print     every third    word from   this txt file

或此类型 -

 I want to print every third word from this txt file

但输出是 -

to third this