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;
}
来源
2016-02-12 02:19:38
Jts