我是 C++ 的新手,我只是不知道如何使用任何多维数组。我想做这样的事情:
input number of product: number; //the products' name can be 7 with NULL char. (max 6)
char arr[number][7];
行得通。但是当我想在 for loop(i) 中这样做时:
cin>>arr[i][7];
而且我不知道编译器到底在做什么?
我只想要:
arr[0][7]=apple;
arr[1][7]=orange;
请问我该怎么做?
最佳答案
#include <string>
#include <vector>
既然每个人都在推荐它,我想我应该为您勾勒出选项。
请注意,您可能会在 10 毫秒内由 3 个不同的人得到这种答案,如果您提供了一个简短的有效示例代码片段(翻译代码 1:1 效率更高而不是“想出”你可能认识的例子)
给你:
std::vector<std::string> strings
strings.push_back("apple");
strings.push_back("banana");
// or
std::string s;
std::cin >> s; // a word
strings.push_back(s);
// or
std::getline(std::cin, s); // a whole line
strings.push_back(s);
// or:
// add #include <iterator>
// add #include <algorithm>
std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::back_inserter(strings));
直接寻址也是可能的:
std::vector<std::string> strings(10); // 10 empty strings
strings[7] = "seventh";
编辑以回应评论:
const char* eighth = "eighth";
if (strings[7] != eighth)
{
// not equal
}
// If you really **must** (read, no you don't) you can get a const char* for the string:
const char* sz = strings[7].c_str(); // warning:
// invalidated when `strings[7]` is modified/destructed
关于c++ - 如何在循环中使用多维字符或字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8326374/