初始化程序太多导致错误

时间:2016-02-12 02:13:08

标签: c++ visual-studio robotics

我需要创建一个不同颜色的数组,第二个数组将用于对象的数量,因此检测到的第一个对象将循环遍历所有颜色。我无法在“终端”框中显示颜色列表。

这就是我所要做的:

#include < iostream>
#include < string.h>
using namespace std;
int main() {
    string Color[11] = { "Red", "Blue", "Green", "Purple", "Yellow", "Black", "White", "Orange", "Brown", '\0' };
    cout << Color << endl;
    return 0;
}

2 个答案:

答案 0 :(得分:1)

1

正确的包含文件是<string>string.h是C,这是C ++。

2

std::string个对象用字符串初始化。

'\0'

不是字符串。这是一个单一的角色。它不属于初始化列表。

3

我在你的数组中计算了9个字符串(虚假的&#39; \ 0&#39;排除在外),而不是11个。额外的数组元素不会受到伤害,但它们是不必要的。

4

cout << Color << endl;

Color是一个数组。您不能将整个数组写入std::cout,只能一个元素,一次一个字符串。您需要简单地遍历Color数组,并将每个单独的数组元素写入std::cout。大概是有意义的分隔符。

答案 1 :(得分:0)

Color不是单个字符串,它是一个字符串数组,因此您必须执行循环来打印每个字符串。此外,你需要找一个学习C ++的好地方,因为你正在做的事情来自C。

<string.h>用于C字符串,<string>用于C ++ std :: string

数组末尾的'\0'也是C语言。

const char * pointers[] = {"HELLO","WORD", '\0' }; // the third element is a NULL pointer (in C++11 now you can use nullptr)

int i = 0;
while (pointers[i] != nullptr)
    std::cout << pointers[i++];

Demo

#include <iostream>
#include <string>

using namespace std;
int main() {
    // You don't need to specify the size, the compiler can calculate it for you.
    // Also: a single string needs a '\0' terminator. An array doesn't.
    string Color[] = { "Red", "Blue", "Green", "Purple", "Yellow",
                        "Black", "White", "Orange", "Brown"};

    for (const auto& s : Color) // There's multiple ways to loop trought an array. Currently, this is the one everyone loves.
        cout << s << '\t'; // I'm guessing you want them right next to eachother ('\t' is for TAB)

    // In the loop &s is a direct reference to the string stored in the array.
    // If you modify s, your array will be modified as well.
    // That's why if you are not going to modify s, it's a good practice to make it const.

    cout << endl; // endl adds a new line

    for (int i = 0; i < sizeof(Color) / sizeof(string); i++) // Old way.
        cout << Color[i] << '\t';
    cout << endl;

    for (int i = 3; i < 6; i++) // Sometimes u just want to loop trough X elements
        cout << Color[i] << '\t';
    cout << endl;

    return 0;
}