有什么不对我的code,从字符串中删除元音? [英] What is wrong with my code that removes vowels from strings?

查看:212
本文介绍了有什么不对我的code,从字符串中删除元音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的编程和我决定做一些简单的编程练习。
目前的挑战是从用户输入字符串中删除所有的元音。
我已经写了code,我不知道为什么它不工作。

I'm new to programming and I've decided to do some simple programming exercises. The challenge is to remove all vowels from a user inputted string. I've already wrote the code and I don't know why it isn't working.

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

bool isVowel(char ch)
{
    char charToBeTested = tolower(ch);
    if(charToBeTested == 'a' || 'e' || 'i' || 'o' || 'u')
        return true;
    else
        return false;
}

int main()
{
    int i;
    char formattedString[80];

    printf("Enter a string: ");
    scanf("%s", &formattedString);

    for(i = 0; i < strlen(formattedString); i++)
    {
        if(isVowel(formattedString[i]) == true)
        {
            formattedString[i] = ' ';
        }
    }

    printf("%s", formattedString);
    return 0;
}

所有它应该做的是检查每一个角色在字符串中,看看它是否是一个元音。如果它是一个元音,请用空格当前字符。我会写功能后以删除空格。

All it is supposed to do is check every character in the string and see if it's a vowel. If it's a vowel, replace the current character with a space. I will write the function to remove the spaces later.

所有帮助AP preciated,你是这样一个noob对不起!

All help is appreciated, sorry for being such a noob!

推荐答案

这code不会做你认为它的作用:

This code doesn't do what you think it does:

if (charToBeTested == 'a' || 'e' || 'i' || 'o' || 'u') {
    ...
}

ç间$ P $点这是

C interprets this as

if ((charToBeTested == 'a') || 'e' || 'i' || 'o' || 'u') {
    ...
}

在这里, || 运营商被直接应用到字符文字'E''我'等由于C对待任何非零值是真实的,这句话始终计算为真。

Here, the || operator is being applied directly to the character literals 'e', 'i', etc. Since C treats any nonzero value as "true," this statement always evaluates to true.

要解决这个问题,请尝试重写它是这样的:

To fix this, try rewriting it like this:

if (charToBeTested == 'a' || 
    charToBeTested == 'e' || 
    charToBeTested == 'i' || 
    charToBeTested == 'o' || 
    charToBeTested == 'u') {
    ...
}

另外,使用开关语句:

switch (charToBeTested) {
    case 'a': case 'e': case 'i': case 'o': case 'u':
        return true;
    default:
       return false;
}

此外,您可能需要使用 tolower的这样的测试是不区分大小写。

Also, you might want to use tolower so that the testing is done case-insensitively.

希望这有助于!

这篇关于有什么不对我的code,从字符串中删除元音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆