【问题标题】:How can I take each word from an array alone and test if it fits specific conditions? (C)如何单独从数组中获取每个单词并测试它是否符合特定条件? (C)
【发布时间】:2015-12-20 09:23:01
【问题描述】:

我正在尝试创建一个程序,它从文本文件中读取一个句子,然后只打印不以元音开头的单词。

所以我编写了一个程序,它读取文本文件并将句子复制到一个数组中。现在,我正在努力实际测试数组中的每个单词是否符合条件(不是以元音开头)。

到目前为止,我只能通过使用 strtok 函数并使用空格作为分隔符来做到这一点,但这也消除了句子中的空格,这不是预期的结果。

例如,如果文本文件包含以下句子: 一天一个苹果,医生远离我。

输出将是: 日托医生

虽然所需的输出是: 天天看医生

这是我的程序:


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

int vowelwords();

int main() 
{

    vowelwords();
    return 0;
}

int vowelwords()
{
    FILE *fPtr;
    char text[50];
    fPtr = fopen("TEXT1.txt","r"); //to open file

    if (fPtr == NULL) //Catch error in fopen function
    {
        printf("Error in opening file\n");
        return 1;
    } 

    fgets(text, 50, fPtr);
    fclose(fPtr);

    char *c;
    c = strtok(text," ");

    while(c!= NULL) 
    {
        if(c[0]=='a'||c[0]=='A'||c[0]=='e'||c[0]=='E'||c[0]=='u'||
           c[0]=='U'||c[0]=='i'||c[0]=='I'||c[0]=='o'||c[0]=='O')
        {
        }

        else  
        {
            printf("%s", c);
        }  

        c = strtok(NULL," ");       
    }

    printf("\n");
}

【问题讨论】:

  • 为什么不给printf("%s ", c); 增加一个空格?
  • 非常感谢!我不知道我怎么没有想到这一点。

标签: c arrays function while-loop words


【解决方案1】:

在打印时,在函数int vowelwords() 中的printf 中留一个空格-

printf("%s ", c);
          ^ leave a space

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多