2016-02-12 31 views
-1

我需要创建一个不同颜色的数组,第二个数组将是对象的数量,所以检测到的第一个对象将遍历所有的颜色。我无法获取要在终端框中显示的颜色列表。错误与太多的初始化程序

这是我不得不远:

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

是错的,如果你需要的是的std :: string,这将是,你也声明的大小11的阵列,但我只在初始化计10个值。你忘记了吗?第三,你不能打印这样的数组。 (PS:使用命名空间标准;被认为是不好的做法,习惯于用std::来预先修正东西:) – Borgleader

回答

1

1.

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

2.

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

'\0' 

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

3.

我算你阵列九串(乱真“\ 0”除外),而不是11的额外数组元素不会伤人,但他们是没有必要的。

4.

cout << Color << endl; 

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

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; 
} 
+0

我推荐使用自动数组大小:'string Color [] = {...}',而不是声明一个11初始化器中包含9个字符串的元素数组。也许实际上提到你为什么拿出空字符。 – paddy

+0

谢谢!我试试看看会发生什么! –