在c++中处理数组的问题
Issue with processing an Array in C++
我试图创建一个数组,让用户输入最多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]
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 输入std::数组时出现问题
- 类对象数组的问题会导致崩溃
- 传递二维数组时出现问题
- 从 C++ 中的函数返回数组地址问题
- 使用数组时出现问题
- 打印问题.我在数组中打印值时遇到一些问题
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 将字节数组转换为带有字节序问题的指针
- C++ 填充数组时遇到问题
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 当我尝试通过 arduino 上的引用传递布尔数组时出现问题
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- 编写 cin.get() 以接收字符数组时出现问题
- 在 C++ Consol 中的数组中执行用户命令时出现问题
- 存储另一个函数返回的布尔数组时遇到问题
- 当我在 CLion 中读取数组中的 txt 文件时C++编码问题
- 运行时C++数组初始化问题
- 我在解决此错误时遇到问题.我正在努力在主函数中传递数组