【问题标题】:0 appearing on a c++ code after input , and array doesnt working0 在输入后出现在 c++ 代码上,并且数组不起作用
【发布时间】:2022-01-12 14:57:00
【问题描述】:

所以我做了一个程序来计算句子中有多少元音(a,e,i,o u)。

如果我输入:

  • 2
  • 你好
  • 世界

iw 将输出:

  • 0
  • 0
  • 2
  • 3

我想要的输出:

  • 2
  • 1
  • //因为hello有2个元音,world有1个元音。

我已经尝试了很多方法,但仍然是错误

这是我的代码

#include<iostream>
#include<string>
using namespace std;

string stringsoal2 ;
int repeat, x, sum = 1, jumlahvokal = 0, jumlahvokalarr, memory_vokal[100];


int main(){
    cin >> repeat;
        for (int z = 0; z <= repeat; z++) {
            getline(cin, stringsoal2);
            for (int i = 0; i < stringsoal2.length(); i++) {
                if ((stringsoal2[i] == ('a')) || (stringsoal2[i] == ('i')) || (stringsoal2[i] == ('u')) || (stringsoal2[i] == ('e')) || (stringsoal2[i] == ('o'))) {
                    jumlahvokal++;
                    
                }
                
            }
            memory_vokal[sum] = jumlahvokal;
            sum++;

        }


        for (int i = 0; i < sum; i++) {
            cout << memory_vokal[i] << endl;
        }

        return 0;
}

【问题讨论】:

  • 为什么 3 个用户输入应该只导致 2 个输出?
  • 你得到什么错误?
  • 您需要为每个单词重置jumlahvokal
  • 另外,使用sum = 1,您将落后一位。使用sum = 0。或者只使用repeat 而不是sum
  • for (int z = 0; z &lt;= repeat; z++) 这个循环执行了多少次?

标签: c++ arrays string


【解决方案1】:

我可以为您的问题提供解决方案。

#include <iostream>
#include <vector>
using namespace std;
void solve()
{
    vector<char> vowels={'a', 'e', 'i', 'o', 'u'};
    vector<string> words={"hello", "world"};
    for(int i=0; i<words.size(); ++i)
    {
        int count=0;
        for(int j=0; j<words[i].size(); ++j)
        {
            for(char vowel : vowels)
            {
                if(vowel==words[i][j])
                {
                    ++count;
                }
            }
        }
        cout<<"word <- "<<words[i]<<", count <- "<<count<<endl;
    }
    return;
}
int main()
{
    solve();
    return 0;
}

结果如下:

word <- hello, count <- 2
word <- world, count <- 1

【讨论】:

  • std::unordered_set&lt;char&gt;std::vector&lt;char&gt; 更适合这种情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 2020-02-02
  • 2013-01-15
  • 1970-01-01
相关资源
最近更新 更多