如何检查一组字符是否包含在 C++ 中的字符数组中?
How to check if a set of characters are contained in a character array in C++?
这是我在 Whosebug 上的第一个问题。我希望找到我要找的东西。我试图找到一种方法来检查一组字符是否属于一个数组。这是在 class 中被问到的,我试图弄明白,但在输出中什么也没得到。
创建一个包含 10 个字符的数组,包含从 a 到 j 的字母。
检查数组是否包含 a、b、c 字符值。
如果是,让用户输入一个名字,如果输入的名字是TEST
显示 TEST 5 次。
我知道 if 语句有问题。请指教!谢谢:)
#include <iostream>
#include<string>
using namespace std;
int main()
{
string name;
char arr[10] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
for (int x = 0; x < 10; x++)
{
if ((arr[x] == 'a') && (arr[x] == 'b') && (arr[x] == 'c'))
{
cout << "Enter a name" << endl;
cin >> name;
if (name == "TEST")
for (int a = 0; a < 5; a++)
cout << "TEST" << endl;
}
}
system("pause");
return 0;
}
查看代码片段以了解您的理解:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
char arr[10] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
bool found_a = false;
bool found_b = false;
bool found_c = false;
for (int x = 0; x < 10; x++) {
if( arr[x] == 'a' ) {
found_a = true;
} else if( arr[x] == 'b' ) {
found_b = true;
} else if( arr[x] == 'c' ) {
found_c = true;
}
if(found_a == true && found_b == true && found_c == true) {
cout << "Enter a name" << endl;
cin >> name;
if (name == "TEST") {
for (int a = 0; a < 5; a++) {
cout << "TEST" << endl;
}
}
break;
}
}
system("pause");
return 0;
}
这是我在 Whosebug 上的第一个问题。我希望找到我要找的东西。我试图找到一种方法来检查一组字符是否属于一个数组。这是在 class 中被问到的,我试图弄明白,但在输出中什么也没得到。
创建一个包含 10 个字符的数组,包含从 a 到 j 的字母。 检查数组是否包含 a、b、c 字符值。 如果是,让用户输入一个名字,如果输入的名字是TEST 显示 TEST 5 次。
我知道 if 语句有问题。请指教!谢谢:)
#include <iostream>
#include<string>
using namespace std;
int main()
{
string name;
char arr[10] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
for (int x = 0; x < 10; x++)
{
if ((arr[x] == 'a') && (arr[x] == 'b') && (arr[x] == 'c'))
{
cout << "Enter a name" << endl;
cin >> name;
if (name == "TEST")
for (int a = 0; a < 5; a++)
cout << "TEST" << endl;
}
}
system("pause");
return 0;
}
查看代码片段以了解您的理解:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
char arr[10] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
bool found_a = false;
bool found_b = false;
bool found_c = false;
for (int x = 0; x < 10; x++) {
if( arr[x] == 'a' ) {
found_a = true;
} else if( arr[x] == 'b' ) {
found_b = true;
} else if( arr[x] == 'c' ) {
found_c = true;
}
if(found_a == true && found_b == true && found_c == true) {
cout << "Enter a name" << endl;
cin >> name;
if (name == "TEST") {
for (int a = 0; a < 5; a++) {
cout << "TEST" << endl;
}
}
break;
}
}
system("pause");
return 0;
}