c++ - 如何在循环中使用多维字符或字符串数​​组

标签 c++ arrays string char multidimensional-array

我是 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/

相关文章:

c++ - 在相同状态类型的各种屏幕之间切换?

c++ - 官方 Windows C/C++ 编译器和 C 库

c++ - 清除 eof 位不适用于 while 循环

mysql - 从Mysql中的日期范围中提取所有日期

java - 从txt列表到字符串数组

python - 为什么 Python 正则表达式字符串有时可以在不使用原始字符串的情况下工作?

C++ 将接口(interface)连接到基类

"simple"多级数组上的 PHP Array_filter

JavaScript 数组 |如果值包含字符串,则返回索引

javascript - `toLowerCase` 可以更改 JavaScript 字符串的长度吗?