所以我正在制作一个小程序。你输入一个字符串,然后我的程序输出该字符串,除了a是辅音现在是“C”,元音是“V”。为什么当我输入“时它输出错误直升机”也许还有其他词?
#include <iostream>
#include <string>
using namespace std;
int main()
{
const char con[]={'b','c','d','f','g','h','i','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z','B','C','D','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','V','W','X','Y','Z'};
const char vow[]={'a','e','i','o','u','A','E','I','O','U'};
const char car[]={'!','@','#','$','%','^','&','*','?','+','-','_','0','1','2','3','4','5','6','7','8','9'};
int scon=sizeof(con)/sizeof(con[0]);
int svow=sizeof(vow)/sizeof(vow[0]);
int scar=sizeof(car)/sizeof(car[0]);
string x;
int i,j;
getline(cin,x);
for(i=0;i<x.length();i++){
if(x[i]==' '){
cout<<" ";
}
else{
for(j=0;j<scon;j++){
if(x[i]==con[j]){
cout<<"C";
break;
}
}
for(j=0;j<svow;j++){
if(x[i]==vow[j]){
cout<<"V";
break;
}
}
for(j=0;j<scar;j++){
if(x[i]==car[j]){
cout<<x[i];
break;
}
}
}
}
return 0;
}
很抱歉我的代码一团糟。
最佳答案
除了 @1201ProgramAlarm 已经指出的明显内容('i'
位于辅音列表中)之外,其中还有很多非常不惯用的代码 - 就像您在 C 中编码的方式一样,而且 C 质量相当低(无意冒犯)。
虽然没有完美的代码,但也许您可能会从查看用实际 C++ 编写的相同(嗯,非常相似......)程序中受益。只是为了了解您可以做什么。
#include <iostream>
#include <string>
#include <string_view>
#include <locale>
// "using namespace" is a habit that tends to get in the way
// once you start including headers from multiple namespaces,
// so while it has its place in quick one-shots, personally I
// got into the habit of fully qualifying.
int main()
{
// This is, of course, very non-international, but I will
// let this slide and not drag the ICU library into this...
std::string_view const consonants { "bcdfghjklmnpqrstvwxyz" };
std::string_view const vowels { "aeiou" };
std::string input;
// while instead of if allows you to make multiple lines of
// input. <Ctrl>-D to end the program (<Ctrl>-Z <Enter> on
// Windows).
while ( getline( std::cin, input ) )
{
// Range-For eliminates the need for loop counters / iterators
for ( auto const c : input )
{
if ( consonants.find( std::tolower( static_cast<unsigned char>( c ) ) ) != std::string::npos )
{
std::cout << 'C';
}
else if ( vowels.find( std::tolower( static_cast<unsigned char>( c ) ) ) != std::string::npos )
{
std::cout << 'V';
}
else if ( std::isprint( static_cast<unsigned char>( c ) ) )
{
// Not exactly the same as your list of digits
// and punctuation, but similar, and showing the
// use of character types. isprint() is also true
// for ' '.
std::cout << c;
}
}
// std::endl ensures a flush of the write buffer
std::cout << std::endl;
}
}
关于c++ - 我的辅音/元音替换器有什么错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61737683/