加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

迭代字符串,并切换语句:C

发布时间:2020-12-16 10:44:31 所属栏目:百科 来源:网络整理
导读:我正在写一些代码,并遇到了一些麻烦.我想编写一个函数来检查一个字符串是否有任何元音,并尝试通过一个带有switch语句的for循环来完成它.显然,它不起作用,并且由于某种原因永远不会返回真实. bool scanStr(string userInp) { for (int i = 0; i userInp.size(
我正在写一些代码,并遇到了一些麻烦.我想编写一个函数来检查一个字符串是否有任何元音,并尝试通过一个带有switch语句的for循环来完成它.显然,它不起作用,并且由于某种原因永远不会返回真实.

bool scanStr(string userInp) {
    for (int i = 0; i < userInp.size(); i++) {
        switch (userInp[i])
        {
        case 'a':
        case 'A':
        case 'e':
        case 'E':
        case 'i':
        case 'I':
        case 'o':
        case 'O':
        case 'u':
        case 'U':
        case 'y':
        case 'Y':
            return true;
            break;
        default:
            return false;
        }
    }
}

我试着测试一下程序是否实际上正在迭代字符串,它是,所以我不明白为什么在函数中,它总是返回false?

int main() {
    string userInp;
    string pigLatin;

    cout << "Please enter a string to convert to pig Latin: " << endl;
    cin >> userInp;
    cout << endl;

    // tests
    for (int i = 0; i < userInp.size(); i++) { //checking if it actually iterates
        cout << userInp[i];
    }
    cout << endl;

    if (scanStr(userInp))
        cout << "it has a vowel" << endl;
    else
        cout << "no vowel" << endl;

    system("pause");
    return 0;
}

起初我认为这是因为即使在最后一个案例之后有一个中断语句,循环仍然继续,但我不完全确定这是否是原因.

有任何想法吗?

解决方法

问题是,如果任何字符不是元音,那么该函数会立即返回false.也使用const&amp ;. const允许你传递const字符串和引用节省一些时间,因为C不必复制整个字符串.

bool scanStr(const string & userInp) {
    for (int i = 0; i < userInp.size(); i++) {
        switch (userInp[i])
        {
        case 'a':
        case 'A':
        case 'e':
        case 'E':
        case 'i':
        case 'I':
        case 'o':
        case 'O':
        case 'u':
        case 'U':
        case 'y':
        case 'Y':
            return true;
            break;
        }
    }
    return false;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读