C++ 如何保存没有某些字符的字符串?
我正在编写一个程序,它给出的输入字符串没有元音。但它只给出字符串的第一个字符。下面是代码:C++ 如何保存没有某些字符的字符串?,c++,C++,我正在编写一个程序,它给出的输入字符串没有元音。但它只给出字符串的第一个字符。下面是代码: #include<iostream> using namespace std; int main(){ char ch; while(cin.get(ch)){ cout<<ch; char a=cin.peek(); while( a==65 || a==69 || a==73 || a==79 || a==
#include<iostream>
using namespace std;
int main(){
char ch;
while(cin.get(ch)){
cout<<ch;
char a=cin.peek();
while( a==65 || a==69 || a==73 || a==79 || a==85 || a==97 || a==101 || a==105 || a==111 || a==117)
cin.ignore(1 , a);
}
return 0;
}
要解决这样的问题,首先要将问题分解成更小的部分。一种可能的分解是: 是否还有字符需要从输入中读取?不:太好了,我们完成了! 读入字符 这个字符是元音吗?是:转到1。 输出字符 转到1。 然后在代码中,您可以将其转换为:
// 1) Are there characters still to read?
while (std::cin.good())
{
// 2) Read in a character
char ch;
std::cin.get(ch);
// 3) Is the character a vowel?
// For the test for a vowel, you can use something similar to
// what you have at the moment, or better still: consider
// writing a function like isVowel in @Shreevardhan answer.
if ( /* TODO: Test if the character is a vowel... */)
{
// Skip the rest of the loop and go back to 1
continue;
}
// 4) Output the good character
std::cout << ch;
// 5) Reached the end of the loop, so goto 1
}
把你的问题分解成更小的部分是一个好习惯。我经常在开始一个新项目时,先写一个列表/注释,甚至画一个流程图,将问题分解成更易于管理的部分。类似的内容
#include <iostream>
using namespace std;
bool isVowel(char c) {
c = tolower(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
int main() {
char c;
while (cin.get(c))
if (!isVowel(c))
cout << c;
return 0;
}
将您的存储逻辑添加到其中
更多的C++语言代码
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
string s;
getline(cin, s);
s.erase(remove_if(s.begin(), s.end(), [](char c) {
c = tolower(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}), s.end());
cout << s;
return 0;
}
请参阅。其他答案显示了如何以更直观的方式解决此问题。 无论如何,查看代码时请考虑以下内容:
while( a==65 || a==69 || a==73 || a==79 || a==85 || a==97 || a==101 || a==105 || a==111 || a==117)
cin.ignore(1 , a);
当您使用a值周围的条件执行while循环时,并且作为cin.ignore1,a不会更改a的值,除非抛出异常,否则您永远不会离开此循环,对吗?也许您可以尝试使用boost库
#include <boost/algorithm/string.hpp>
boost::erase_all(str, "a");
此代码中没有字符串。char是一种包含单个字符的类型。查找std::string以及如何使用它。您的问题不是很清楚。您的问题提到字符串,但代码中没有字符串或字符数组。它不尝试存储任何字符或显示任何内容。您是否正在寻找一种解决方案,在输入时检查每个字符,或者如果输入整个字符串,然后删除元音,这是否正常?这不是问题所在,但不要在字符代码中使用硬编码猜测。while语句应该是whilea='a'| | a=='e'等等,如果我猜对了这些代码的含义的话。或者,更好的是,const char元音[]=aeiouAEIOU;而std::findstd::beginvowels、std::endvowels、ch.则是很好的方法。但有时倒过来比较好。与其检查这个字符是否是元音,不如检查它是否是元音,如果是,就把它写出来。代码变得更加清晰。