简体   繁体   English

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

[英]How to use multidimensional char or string arrays in a loop

I'm so new to C++ and I just can't figure out how to use any multidimesional arrays. 我对C ++很陌生,只是无法弄清楚如何使用任何多维数组。 I want to do something like that: 我想做这样的事情:

input number of product: number; //the products' name can be 7 with NULL char. (max 6)
char arr[number][7];

That works. 这样可行。 But when I want to do that in a for loop(i): 但是,当我想在for循环中执行此操作时:

cin>>arr[i][7];

and I don't know what the hell is compiler doing? 而且我不知道编译器在做什么?

I just want that: 我只想要:

arr[0][7]=apple;
arr[1][7]=orange;

So please how can I do that? 所以,我该怎么做?

#include <string>
#include <vector>

Since everybody is recommending it, I thought I'd sketch the options for you. 既然每个人都在推荐它,我想我应该为您列出一些选择。

Note that you would have gotten this kind of answer in 10 milli-seconds by 3 different persons, if you had supplied a short, working sample code snippet (translating code 1:1 is more efficient than 'thinking up' examples that you might recognize) 请注意, 如果您提供了一个简短且有效的示例代码段, 那么您将在10毫秒内得到3个人的这种回答(翻译代码1:1比您可能会想到的“思考”示例更有效) )

Here you go: 干得好:

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));

Direct addressing is also possible: 也可以直接寻址:

std::vector<std::string> strings(10); // 10 empty strings

strings[7] = "seventh";

Edit in response to comments: 编辑以回应评论:

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

Because arr[i][7] is a char , and in fact one past the last element, which means you may get memory access error. 因为arr[i][7]是一个char ,实际上是最后一个元素之后的一个,这意味着您可能会遇到内存访问错误。

What you want to do maybe cin>>arr[i]; 您想做什么也许cin>>arr[i]; .

How ever, this is not a very good idea, as you cannot control how many characters are read from input, which will easily cause memory overrun. 但是,这不是一个好主意,因为您无法控制从输入读取多少个字符,这很容易导致内存溢出。

The easy way would be using std::vector<std::string> as others have suggested. 如其他人所建议的那样,简单的方法是使用std::vector<std::string>

Unless you have a real reason (which you mustn't hide from us), make as Björn says and use a vector of strings. 除非您有真正的理由(一定不能对我们隐瞒),否则请按比约恩所说的那样使用字符串向量。 You can even do away with the initial request for the total size: 您甚至可以取消对总大小的初始请求:

#include <string>
#include <vector>
#include <iostream>

std::vector<std::string> fruits;
std::string line;

while (std::getline(std::cin, line))
{
  fruits.push_back(line);
}

Let's test: 让我们测试一下:

std::cout << "You entered the following items:\n";
for (auto const & f : fruits) std::cout << "* " << f << "\n";

You have a two dimensional array of char 您有一个二维char数组

char arr[number][7];

And then trying to assign a string (char* or const char*) to them which will not work. 然后尝试为它们分配一个字符串(char *或const char *),该字符串将不起作用。 What you can do here is assign a character, for example: 您在这里可以做的就是分配一个字符,例如:

arr[0][1] = 'a';

If you can I would recommend using std::vector and std::string it would make things much clearer. 如果可以的话,我建议您使用std::vectorstd::string来使事情变得更加清晰。 In your case you could do 在你的情况下你可以做

cin>>arr[i];

But I would not recommend it as you could only store up to 6 character char* strings (plus the null terminator). 但我不建议您这样做,因为您最多只能存储6个字符的char *字符串(加上空终止符)。 You can also have an array of char* 您也可以拥有一个char *数组

char* arr[number];

then dynamically allocate memory to store the strings. 然后动态分配内存以存储字符串。

strcpy(&arr[0], "apple");
strcpy(&arr[1], "orange");

but for C++ is better to use std::vector<std::string> for array of strings 但是对于C ++来说,最好将std::vector<std::string>用于字符串数组

Using std::vector and std::string will usually save you headaches once you understand them. 一旦理解了std :: vector和std :: string,它们通常会为您省去头痛。 Since you are brand new to C++, it might be useful to understand what is going on with two-dimensional arrays anyhow. 由于您是C ++的新手,因此无论如何了解二维数组的内容可能会很有用。

When you say 当你说

char array[N][M];

With N and M being constants, not variables, you are telling the compiler to allocate N*M items of type char. 由于N和M是常量,而不是变量,所以您要告诉编译器分配char类型的N * M个项目。 There will be a block of memory dedicated to that array of size N*M*sizeof(char). 将有一块专用于大小为N * M * sizeof(char)的数组的内存。 (You can declare an array of anything, not just char. Since sizeof(char) is 1, the memory will be N*M bytes long.) If you looked at raw memory, the first byte in the memory would be where array[0][0] is. (您可以声明任何数组,而不仅仅是char。由于sizeof(char)为1,因此内存将为N * M字节长。)如果查看原始内存,则内存中的第一个字节将位于array [ 0] [0]是。 The second byte would be where array[0][1] is, an so on, for M bytes. 第二个字节将是array [0] [1]所在的位置,依此类推,对于M个字节。 Then you would see array[1][0]. 然后,您将看到array [1] [0]。 This is called row-major order. 这称为行优先顺序。

As @jbat100 mentioned, when you say array[i][j] you are referring to a single character. 正如@ jbat100所提到的,当您说array [i] [j]时,是指一个字符。 When you say array[i], you are referring to the address of row i in the array. 当您说array [i]时,是指数组中第i行的地址。 There is no pointer actually stored in memory, but when you say array[i] the compiler knows that you mean that you want the address of row i in the array: 内存中实际上没有存储任何指针,但是当您说array [i]时,编译器知道您的意思是您想要数组中第i行的地址:

char* row_i = array[i];

Now if i>0, then row_i points to somewhere in the middle of that block of memory dedicated to the array. 现在,如果i> 0,则row_i指向该数组专用内存块中间的某个位置。 This would do the same thing: 这会做同样的事情:

char* row_i = &array[i][0];

If you have a string, "orange" and you know that the length of it is less than M, you can store it in a given row in the array, like this: 如果您有一个字符串“ orange”,并且知道它的长度小于M,则可以将其存储在数组的给定行中,如下所示:

strcpy(array[i], "orange"); // or
array[i][0] = 'o'; array[i][1] = 'a'; ... array[i][6] = 0;

Or you could have said row_i instead of array[i]. 或者,您可以说row_i而不是array [i]。 This copies 7 bytes into the array in the location of row_i. 这会将7个字节复制到row_i位置的数组中。 The strcpy() also copies an extra byte which is a 0, and this is the convention for terminating a character string in C and C++. strcpy()还复制一个额外的字节,该字节为0,这是在C和C ++中终止字符串的约定。 So the 7 bytes are six bytes, 'o', 'r', 'a', 'n', 'g', and 'e', plus a 0 byte. 因此,这7个字节是六个字节,即“ o”,“ r”,“ a”,“ n”,“ g”和“ e”,再加上一个0字节。 Now strcmp(row_i, "orange") == 0. 现在strcmp(row_i,“ orange”)== 0。

Beware that if your string is longer than M, the strcpy and the simple char assignments will not (probably) produce a compile error, but you will end up copying part of your string into the next row. 请注意,如果您的字符串长于M,则strcpy和简单的char赋值不会(可能)产生编译错误,但最终会将部分字符串复制到下一行。

Read about pointers and arrays in a good C/C++ book. 在一本不错的C / C ++书中阅读有关指针和数组的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM