【问题标题】:How to check if a set of characters are contained in a character array in C++?如何检查一组字符是否包含在 C++ 中的字符数组中?
【发布时间】:2016-01-26 22:00:10
【问题描述】:

这是我在 stackoverflow 上的第一个问题。我希望找到我正在寻找的东西。我试图找到一种方法来检查一组字符是否属于一个数组。这是在课堂上被问到的,我试图弄清楚,但输出中什么也没有。

创建一个 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;
}

【问题讨论】:

  • 不需要粗体字,我们不是盲人(我猜我们大多数人)。最好努力正确地格式化你的代码,并解释它到底出了什么问题。另外,您如何看待这种情况if ((arr[x] == 'a') &amp;&amp; (arr[x] == 'b') &amp;&amp; (arr[x] == 'c')) 成为现实?您的意思是实际上使用逻辑或 (||) 吗?
  • 我推荐std::string数据类型和它的一些方法,比如findsubstr
  • 嗨 πάντα ῥεῖ。好吧,我还是不习惯stackoverflow的格式,就是这样。我在stackoverflow上得到了答案。这可以使用三个布尔变量来解决。布尔 b1 = 假;布尔 b2 = 假;布尔 b3 = 假; for (int x = 0; x
  • 你能解释一下什么样的字母同时是'a'、'b'和'c'?因为这就是你的 if() 语句字面意思(双关语不是有意的)检查的内容。

标签: c++ arrays for-loop character


【解决方案1】:

看代码sn-p了解一下:

#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;
}

【讨论】:

    猜你喜欢
    • 2017-01-18
    • 2021-06-10
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 2013-08-16
    • 2015-09-08
    • 2011-02-24
    相关资源
    最近更新 更多