【问题标题】:string.h output words Cstring.h 输出单词 C
【发布时间】:2017-04-23 23:05:36
【问题描述】:

我需要比较一个单词的第一个和最后一个字母;如果这些字母相同,我需要将该单词输出到文件中。 但我从另一个文件中取出单词。我的问题是我无法猜测我应该如何输出所有单词,因为在我的代码中,它只输出第一个单词。所以我明白我没有过渡到别人。

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

int main()
{
    char my_string[256];
    char* ptr;

    FILE *f;
    if ((f = fopen("test.txt", "r"))==NULL) {
        printf("Cannot open  test file.\n");
        exit(1);
    }

    FILE *out;
    if((out=fopen("result.txt","w"))==NULL){
        printf("ERROR\n");
        exit(1);
    }

    fgets (my_string,256,f);
    int i;
    int count = 1;

    printf("My string is %d symbols\n", strlen(my_string));

    for (ptr = strtok(my_string," "); ptr != NULL; ptr= strtok(NULL," "))
    {
        int last = strlen(ptr) - 1;
        if ((last != -1) && (ptr[0] == ptr[last]))
        {
            printf("%s\n",ptr);
        }
    }

    printf("\n%s\n",my_string);
    fprintf(out,"%s\n",my_string);
    system("pause");
    fclose(f);
    fclose(out);

    return 0;
}

在我的第一个文件中有这样的话:

high day aya aya eye that

从第一个文件中我的话,它只输出第一个单词

high

到第二个文件。我期待以下内容:

high aya aya eye

【问题讨论】:

  • 你是什么意思“它只做第一个词”?对于指定的输入,实际和预期的输出是多少?您是否尝试过在调试器中逐行执行代码? my_strlenmystrtok 函数是否正常工作? 为什么你有自己的字符串函数而不是使用标准函数?
  • my_strlenmystrtok 有什么用?你用的是什么库?
  • 这意味着它输出我需要的第一个单词(具有相同的第一个单词和相同的最后一个字母),但有多个。我的功能有效。为了检查我可以使用库 我使用我自己的函数,因为它是这个程序的特殊条件。
  • 好吧,这段代码对我来说看起来不错。我怀疑问题可能在于这些自定义函数。
  • 啊,好吧,但是当我从库中获取这些函数时。还是不行:((

标签: c string io strtok strlen


【解决方案1】:

除了 fprintf 整个字符串的最后,您不会向文件输出任何内容:

fprintf(out,"%s\n",my_string);

您需要在该 for 循环中将 printf("%s\n",ptr); 更改为 fprintf(out,"%s\n",ptr);。否则它只会将所有内容输出到控制台。

【讨论】:

  • 非常感谢!现在我得到了我想要的。这是相当简单的字符串,但我需要它。啊哈哈谢谢谢谢谢谢!!!