在c++中处理数组的问题

Issue with processing an Array in C++

本文关键字:问题 数组 处理 c++      更新时间:2023-10-16

我试图创建一个数组,让用户输入最多80个字符,然后当程序停止时,程序返回每个元音出现在数组中的次数。我上周成功地让它工作了,但是代码丢失了,我不得不从头开始。

编辑:我遇到的问题是,基于当前的结构,所有的计数器仍然返回0在结束。

我记得我使用了下面的编码,但我有计数器实际工作的问题。我想我在循环中有计数器的部分,但我不记得了。

我还希望程序在用户按ENTER时停止,但我不知道这是如何工作的。

如有任何帮助,不胜感激。

#include <iostream> 
#include <iostream>
using namespace std;
int main()
{
    int x = 0;
    char thisArray[80];
    int aCounter = 0, eCounter = 0, iCounter = 0, oCounter = 0, uCounter = 0;
    cout << "Please enter up to 80 characters and you will be told" << endl;
    cout << "how many times each vowel is in the array." << endl;
    do{
        cout << "Please enter a character" << endl;
        cin >> thisArray;
        x++;
    } while (x < 80);

    for (x = 0; x <= thisArray[x]; x++) {
        if (thisArray[x] == 'a')
            aCounter = aCounter + 1;
        else if (thisArray[x] == 'e')
            eCounter = eCounter + 1;
        else if (thisArray[x] == 'i')
            iCounter = iCounter + 1;
        else if (thisArray[x] == 'o')
            oCounter = oCounter + 1;
        else if (thisArray[x] == 'u')
        uCounter = uCounter + 1;
    }
    cout << "Vowel count:" << endl;
    cout << "Total number of A's." << aCounter << endl;
    cout << "Total number of E's." << eCounter << endl;
    cout << "Total number of I's." << iCounter << endl;
    cout << "Total number of O's." << oCounter << endl;
    cout << "Total number of U's." << uCounter << endl;
    system("pause");
}

您使用的do循环不正确。它将尝试读取字符串80次,并且只存储最后一个字符串。每个字符串将只包含非空白字符。

更改do循环,以便每次读取一个字符,使用未格式化的输入,并将所有字符存储在数组中,包括空白字符。

当达到可容纳的字符数限制或遇到换行符时,停止循环。

cout << "Please enter a line of text" << endl;
// Read the characters one by one.
// Don't read more than 79 characters.
// Stop if a newline or EOF is encountered.
int c;
while ( x < 79 && (c = cin.get()) != 'n' && c != EOF )
{
   thisArray[x] = c;
   ++x;
}
// null terminate the string.
thisArray[x] = '';

您的代码中有几个问题。首先,您没有在do...while循环中输入数组。您需要使用索引操作符([])和数组名称:

do{
    cout << "Please enter a character" << endl;
    cin >> thisArray[x];
    x++;            ^^^ input each character into the correct index.
} while (x < 80);

其次,你的for循环有错误的条件。

for (x = 0; x <= thisArray[x]; x++)
应该

for (x = 0; x < 80; x++)
注意,我将<=更改为<,因为数组大小为80,元素为[0,79]