需要阅读空格和其他字符C ++ [英] Need to read white space and other chars C++

查看:93
本文介绍了需要阅读空格和其他字符C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整天都在工作,没有运气。现在是晚上,不知道该怎么办。我的任务是读取用户输入的句子中的元音数量,空格数量和其他字符数量。我知道我需要对空白使用cin.get(ch),但不知道如何使用。我还需要将句子输出到文件中。以下是我到目前为止的内容:

I have been working on this all day with no luck. Its night now and don't know what to do. My assignment is to read number of vowels, number of white spaces, and number of other characters in a user inputted sentence. I know i need to use cin.get(ch) for whitespaces, but don't know how. I also need to output the sentence to a file. Heres what I have so far:

//Get data from user 
cout << "Enter your sentence on one line followed by a # to end it: " << endl;



while (cin >> noskipws >> character && character != '#')
{
    character = static_cast<char>(toupper(character));

    if (character == 'A' || character == 'E' || character == 'I' ||
            character == 'O' ||  character == 'U')
    {
        vowelCount++;
        isVowel = true;

    }

    if (isspace(character))
    {
        whiteSpace++;

    }

    else if (isVowel == true && isspace(character))
    {
        otherChars++;
    }

    outFile << character;

}


outFile << "vowelCount: " << vowelCount << endl;
outFile << "whiteSpace: " << whiteSpace << endl;
outFile << "otherchars: " << otherChars << endl;


推荐答案

#include <iostream>

using namespace std;

int main()
{
    char ch;
    int vowel_count = 0;
    int space_count = 0;
    int other_count = 0;

    cout << "Enter a string ends with #: " << endl;

    while(1)
    {
        cin.get(ch);
        if(ch == '#')
        {
            break;
        }

        if(ch == 'A' || ch == 'a'
            || ch == 'E' || ch == 'e'
            || ch == 'I' || ch == 'i'
            || ch == 'O' || ch == 'o'
            || ch == 'U' || ch == 'u')
        {
            ++vowel_count;
        }
        else if(ch == ' ')
        {
            ++space_count;
        }
        else
        {
            ++other_count;
        }
    }


    cout << "Vowels: " << vowel_count << endl;
    cout << "White spaces: " << space_count << endl;
    cout << "Other: " << other_count << endl;

    return 0;
}

无数组

这篇关于需要阅读空格和其他字符C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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