Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 从文件中分别读取单词_C_String - Fatal编程技术网

C 从文件中分别读取单词

C 从文件中分别读取单词,c,string,C,String,我正在尝试制作一个程序,它可以逐行扫描包含单词的文件,并删除拼写相同的单词(回文) 这是program.c文件: #include <stdio.h> #include <stdlib.h> #include <string.h> #include "header.h" int main(int argc, char **argv) { if(argc != 3) { printf("Wrong parameters"); return 0; }

我正在尝试制作一个程序,它可以逐行扫描包含单词的文件,并删除拼写相同的单词(回文)

这是program.c文件:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "header.h"

int main(int argc, char **argv)
{
if(argc != 3)
{
   printf("Wrong parameters");
   return 0;
}
FILE *data;
FILE *result;
char *StringFromFile = (char*)malloc(255);
char *word = (char*)malloc(255);

const char *dat = argv[1];
const char *res = argv[2];

data = fopen(dat, "r");
result =fopen(res, "w");

while(fgets(StringFromFile, 255, data))
{
    function1(StringFromFile, word);
    fputs(StringFromFile, result);
}
free(StringFromFile);
free (word);
fclose(data);
fclose(result);
return 0;
}
这是函数文件:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "header.h"

void function1(char *StringFromFile, char *word)
{
int StringLength = strlen(StringFromFile);
int WordLength;
int i;
int p;
int k;
int t;
int m;
int match;
for(i = 0; i < StringLength; i++)
{   k=0;
    t=0;
    m=i;
if (StringFromFile[i] != ' ')
{   while (StringFromFile[i] != ' ')
    {
        word[k]=StringFromFile[i];
        k=k+1;
        i=i+1;
    }
//printf("%s\n", word);
WordLength = strlen(word)-1;
p = WordLength-1;
match=0;
while (t <= p)
{
    if (word[t] == word[p])
        {
            match=match+1;
        }
    t=t+1;
    p=p-1;
}
if ((match*2) >= (WordLength))
{
    moving(StringFromFile, &m, StringLength, WordLength);
}
}
}

}

void moving(char *StringFromFile, int *index, int StringLength, int WordLength)
{   int i;
    int q=WordLength-1;
    for(i = *index; i < StringLength; i++)
{
    StringFromFile[i-1] = StringFromFile[i+q];
}
*(index) = *(index)-1;
}
以下是程序读取的单独单词:

abcba
rttta
plllp
aaaaaaaaaaaa
ababa
abbbba
kede
这是结果文件:

abcba rtttp



kede
如果一行中只有一个单词,它就可以正常工作,但是如果有多个单词,它就会出错。感谢您的帮助。

#包括
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "header.h"

# define MAX 255

int Find_Number_Words_in_Line( char str[MAX] )
{
   char *ptr;
   int count = 0;
   int j;

   /* advance character pointer ptr until end of str[MAX] */
   /* everytime you see the space character, increase count */
   /* might not always work, you'll need to handle multiple space characters before/between/after words */

   ptr = str;
   for ( j = 0; j < MAX; j++ )
   {
      if ( *ptr == ' ' )
         count++;
      else if (( *ptr == '\0' ) || ( *ptr == '\n' ))
         break;

      ptr++;
   }

   return count;
}

void Extract_Word_From_Line_Based_on_Position( char line[MAX], char word[MAX], const int position )
{
   char *ptr;

   /* move pointer down line[], counting past the number of spaces specified by position */
   /* then copy the next word from line[] into word[] */
}


int Is_Palindrome ( char str[MAX] )
{
   /* check if str[] is a palindrome, if so return 1, else return 0 */
}


int main(int argc, char **argv)
{
   FILE *data_file;
   FILE *result_file;
   char *line_from_data_file = (char*)malloc(MAX);
   char *word = (char*)malloc(MAX);
   const char *dat = argv[1];
   const char *res = argv[2];
   int j, n;

   if (argc != 3)
   {
      printf("Wrong parameters");
      return 0;
   }

   data_file = fopen(dat, "r");
   result_file = fopen(res, "w");

   fgets( line_from_data_file, MAX, data_file );
   while ( ! feof( data_file ) )
   {
       /*
          fgets returns everything up to newline character from data_file,
          function1 in original context would only run once for each line read
          from data_file, so you would only get the first word

             function1( line_from_data_file, word );
             fputs( word, result_file );
             fgets( line_from_data_file, MAX, data_file );

          instead try below, you will need to write the code for these new functions
          don't be afraid to name functions in basic English for what they are meant to do
          make your code more easily readable
       */

      n = Find_Number_Words_in_Line( line_from_data_file );
      for ( j = 0; j < n; j++ )
      {
         Extract_Word_From_Line_Based_on_Position( line_from_data_file, word, n );
         if ( Is_Palindrome( word ) )
            fputs( word, result_file );  /* this will put one palindrome per line in result file */
      }

      fgets( line_from_data_file, MAX, data_file );
   }
   free( line_from_data_file );
   free( word );

   fclose( data_file );
   fclose( result_file );

   return 0;
}
#包括 #包括 #包括“header.h” #定义最大值255 int查找行中的单词数(char str[MAX]) { char*ptr; 整数计数=0; int j; /*将字符指针ptr提前到str结束[MAX]*/ /*每次看到空格字符时,增加计数*/ /*可能并不总是有效,您需要在单词之前/之间/之后处理多个空格字符*/ ptr=str; 对于(j=0;j
要跟进评论,您可能有点过虑了。要检查文件每行中的每个单词是否都是回文,有两个部分的问题。(1) 阅读每一行(
fgets
可以),以及(2)将每一行分解为单独的单词(标记),以便您可以测试每个标记是否是回文

当使用
fgets
读取每一行时,一个以
fgets
返回为条件的简单while循环就可以了。e、 例如,使用足够大的缓冲区
buf
MAXC
chars),并打开
FILE*
stream
fp
进行读取,您可以执行以下操作:

while (fgets (buf, MAXC, fp)) { /* read each line */
    ...                         /* process line */
}
(您可以测试读入
buf
的行的长度小于
MAXC
字符,以确保您读取了完整的行,否则,在下一次循环迭代中,任何未读的字符都将放入
buf
中。此检查以及您希望如何处理它,留给您。)

读取行后,您可以使用一对简单的指针(开始指针和结束指针)遍历
buf
,也可以使用
strtok
,让它根据传递给它的一组分隔符返回指向行中每个单词开头的指针。例如,要将一行拆分为单词,您可能希望使用诸如
“\t\n,:;!?”
之类的分隔符,以确保只使用单词,而不是使用标点符号的单词(例如,在
“坐在这里。”
,您希望
“坐在这里”
,而不是
“这里”。

使用strtok很简单。在第一次调用时,您传递包含要标记的字符串的缓冲区的名称和一个指向包含分隔符的字符串的指针(例如上面的
strtok(buf,delims)
),然后对于后续的每个调用(直到到达行的末尾),您使用
NULL
作为缓冲区的名称(例如
strtok(NULL,delims)
)您可以调用它一次,然后循环直到返回
NULL
,也可以使用单个
for
循环来完成所有操作,因为
for
允许将初始条件设置为语句的一部分,例如,使用单独的调用:

char  *delims = " \t\n.,:;";    /* delimiters */
char *p = strtok (buf, delims); /* first call to strtok */

while ((p = strtok (NULL, delims))) {  /* all subsequent calls */
    ... /* check for palindrome */
}
或者,您可以在
for
循环中进行初始调用和所有后续调用:

/* same thing in a single 'for' statement */
for (p = strtok (buf, delims); p; p = strtok (NULL, delims)) {
    ... /* check for palindrome */
}
现在,您需要检查回文了。这是一个相当容易的过程。找到标记的长度,然后使用字符串索引,或者简单地使用指向第一个和最后一个字符的指针,从每个标记的末尾到中间,确保字符匹配。对于第一个不匹配,您知道标记不是回文。我发现开始和结束指针与操作sting索引一样简单,例如使用
s
中的标记:

char *ispalindrome (char *s)    /* function to check palindrome */
{
    char *p = s,                   /* start pointer */
        *ep = s + strlen (s) - 1;  /* end pointer  */

    for ( ; p < ep; p++, ep--)  /* work from end to middle */
        if (*p != *ep)          /* if chars !=, not palindrome */
            return NULL;

    return s;
}
示例使用/输出

$ cat dat/palins.txt
abcba rttt plllp
aaaaaaaaaaaa
ababa
abbbba
kede
$ ./bin/palindrome <dat/palins.txt

 line[ 0]:  abcba rttt plllp

 tokens:
  abcba             - palindrome
  rttt              - not palindrome
  plllp             - palindrome

 line[ 1]:  aaaaaaaaaaaa

 tokens:
  aaaaaaaaaaaa      - palindrome

 line[ 2]:  ababa

 tokens:
  ababa             - palindrome

 line[ 3]:  abbbba

 tokens:
  abbbba            - palindrome

 line[ 4]:  kede

 tokens:
  kede              - not palindrome

$./bin/回文abcba是一个palindrom@Fefux这就是问题所在:行中有三个单词包含
abcba
#include <stdio.h>
#include <string.h>

enum { MAXC = 256 };    /* max chars for line buffer */

char *ispalindrome (char *s);

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

    char buf[MAXC] = "",        /* line buffer */
         *delims = " \t\n.,:;"; /* delimiters */
    unsigned ndx = 0;           /* line index */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    while (fgets (buf, MAXC, fp)) { /* read each line */
        char *p = buf;   /* pointer to pass to strtok */
        printf ("\n line[%2u]:  %s\n tokens:\n", ndx++, buf);
        for (p = strtok (buf, delims); p; p = strtok (NULL, delims))
            if (ispalindrome (p))
                printf ("  %-16s  - palindrome\n", p);
            else
                printf ("  %-16s  - not palindrome\n", p);
    }
    if (fp != stdin) fclose (fp);

    return 0;
}

char *ispalindrome (char *s)    /* function to check palindrome */
{
    char *p = s, *ep = s + strlen (s) - 1;  /* ptr & end-ptr */

    for ( ; p < ep; p++, ep--)  /* work from end to middle */
        if (*p != *ep)          /* if chars !=, not palindrome */
            return NULL;

    return s;
}
$ cat dat/palins.txt
abcba rttt plllp
aaaaaaaaaaaa
ababa
abbbba
kede
$ ./bin/palindrome <dat/palins.txt

 line[ 0]:  abcba rttt plllp

 tokens:
  abcba             - palindrome
  rttt              - not palindrome
  plllp             - palindrome

 line[ 1]:  aaaaaaaaaaaa

 tokens:
  aaaaaaaaaaaa      - palindrome

 line[ 2]:  ababa

 tokens:
  ababa             - palindrome

 line[ 3]:  abbbba

 tokens:
  abbbba            - palindrome

 line[ 4]:  kede

 tokens:
  kede              - not palindrome