我正在尝试将变量 char * vowels 和 char * consonants 分别设置为函数 searchVowels 和 searchConsonants 的返回值。
虽然当我测试代码时,上面的变量设置正确但没有传回 main.并在测试期间使用
cout << "text vowels" << vowels << "sametext" << consonants; ///something like this.
现在不显示辅音值。
这是我的代码,任何建议都会非常有帮助。除了我不能使用字符串。(对于一个类)
这也是发布代码的合适方式吗?
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
const int SIZE = 7;
//This function greets the user.
void greetUser();
//This funcion asks for the array of letters.
char * inputLetters(char * inputArray);
//This will capitalize all letters to make them easier for the computer
//to compare.
char * capitalizeLetters(char * inputArray);
//This function will search the array for vowesl. If no vowels no game.
char * searchVowels(char * arrayCopy);
///This function will search the array for consonants.
char * searchConsonants(char * arrayCopy);
//This capitalizes all the letters in the initial array.
char * capitalizeLetters(char * inputArray)
{
for (int i = 0; i < 6; ++i)
{
inputArray[i] = toupper(inputArray[i]);
}
// inputArray = toupper(inputArray);
return inputArray;
}
//This program will search the array for consonants
//and return the consonants array.
char * searchConsonants(char * arrayCopy)
{
char * consonants; consonants = new char[SIZE];
for (int i = 0; i < 6; ++i)
{//I feel like I could make this into a function itself...hmm
if( arrayCopy[i] != 'A' && arrayCopy[i] != 'E'
&& arrayCopy[i] != 'I' && arrayCopy[i] != 'O' &&
arrayCopy[i] != 'U' && arrayCopy[i] != 'Y')
{
consonants[i] = arrayCopy[i];
}
}
return consonants;
}
最佳答案
在方法searchVowels
中,您似乎有以下代码:
if( arrayCopy[i] == 'A' && arrayCopy[i] == 'E'
&& arrayCopy[i] == 'I' && arrayCopy[i] == 'O' &&
arrayCopy[i] == 'U' && arrayCopy[i] == 'Y')
{
arrVowels[i] = arrayCopy[i];
}
您如何期望 arrayCopy[i]
通过检查,因为它不能同时拥有所有元音。我想你正在寻找一个 OR
在这里检查。
if( arrayCopy[i] == 'A' || arrayCopy[i] == 'E'
|| arrayCopy[i] == 'I' || arrayCopy[i] == 'O' ||
arrayCopy[i] == 'U' || arrayCopy[i] == 'Y')
{
arrVowels[i] = arrayCopy[i];
}
在上面的例子中,如果检查通过,它可能会用一些东西填充 arrayVowels
。
此外,您可以将上面的代码变成类似HasVowels()
的函数,它检查arrayCopy
是否在第 i 个索引处有元音,然后使用它在 searchVowels
和 searchConsonants
中。
另一件事是在您的代码中使用“免费”。
在 C++ 中,delete 运算符只能用于指向使用 new operator
分配的内存的指针,而 free()
只能用于指向使用 malloc()
或 NULL 指针分配的内存的指针。
关于c++ - 设置指向函数返回值的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48615886/