C++ 初始值设定项过多时出错

C++ 初始值设定项过多时出错,c++,visual-studio,robotics,C++,Visual Studio,Robotics,我需要创建一个不同颜色的数组,第二个数组将用于对象的数量,因此检测到的第一个对象将循环通过所有颜色。我无法在接线盒中显示颜色列表 这就是我要做的: #include < iostream> #include < string.h> using namespace std; int main() { string Color[11] = { "Red", "Blue", "Green", "Purple", "Yellow", "Black", "White", "

我需要创建一个不同颜色的数组,第二个数组将用于对象的数量,因此检测到的第一个对象将循环通过所有颜色。我无法在接线盒中显示颜色列表

这就是我要做的:

#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;
}
#包括
#包括
使用名称空间std;
int main(){
字符串颜色[11]={“红色”、“蓝色”、“绿色”、“紫色”、“黄色”、“黑色”、“白色”、“橙色”、“棕色”、“'\0'};
cout1

<正确的包含文件<代码> <代码> .<代码>字符串.h <代码>为C,这是C++ + < /P> 二,

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

'\0'
不是字符串。它是单个字符。它不属于初始值设定项列表

三,

我在您的数组中计算了9个字符串(不包括伪“\0”),而不是11个。额外的数组元素没有坏处,但它们是不必要的

四,


<代码> c> <> >代码>颜色< /C>不是一个字符串,它是一个字符串数组,因此,你必须做一个循环来打印每一个字符串,而且,你需要找到一个学习C++的好地方,因为你所做的事情是从C.< <>代码> <代码>是C字符串,<代码> <代码>是C++ C++的::字符串

数组末尾的
'\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++];
const char*pointers[]={“HELLO”,“WORD”,“'\0'};//第三个元素是空指针(在C++11中,现在可以使用nullptr)
int i=0;
while(指针[i]!=nullptr)

如果您需要的是std::string,那么std::cout是错误的,也就是说,您声明了大小为11的数组,但我在初始值设定项中只计算了10个值。您忘记了一个值吗?第三,您不能打印这样的数组。(注意:使用名称空间std;被认为是错误的做法,习惯于使用std:)我建议使用自动数组大小:
string Color[]={…}
,而不是在初始化器中声明一个包含9个字符串的11个元素的数组。并且可能会提到为什么去掉空字符。谢谢!我会尝试一下,看看会发生什么!
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++];
#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;
}