简体   繁体   English

C++中的字符矩阵?

[英]Char matrix in C++?

I have been trying hard with this C++ exercise to no avail.. How do i create a char matrix holding 4 words, with each letter of a word on a char space?我一直在努力尝试这个 C++ 练习,但无济于事..如何创建一个包含 4 个单词的字符矩阵,字符空间上有一个单词的每个字母? This is my attempt.这是我的尝试。
I want to use null to know where the string ends.我想使用 null 来知道字符串在哪里结束。 And due to the instructions of the excercise i have to use a char matrix.由于练习的说明,我必须使用字符矩阵。 As you can see i tried different aproaches with vector[0] and the rest.如您所见,我尝试了使用 vector[0] 和其他方法的不同方法。 Neither of them works.它们都不起作用。

int ax = 3;
char ** vector = new char* [ax+1];
for (int i = 0; i < ax; i++){
    vector[i] = new char[10];
}
vector[0] = "F","u","t","b","o","l";
vector[1] = "AUTOmata";
vector[2] = "fUT";
vector[3] = "auto";
vector[ax+1] = NULL;

I have been trying hard with this C++ exercise to no avail.. How do i create a char matrix holding 4 words, with each letter of a word on a char space?我一直在努力尝试这个 C++ 练习,但无济于事..如何创建一个包含 4 个单词的字符矩阵,字符空间上有一个单词的每个字母?

No problem.没问题。 You can use std::vector and std::string for this task.您可以将std::vectorstd::string用于此任务。 In fact from std::string you can get a C-string (null terminated since you like them) withdata() .事实上,从std::string你可以得到一个带有data()的 C 字符串(空终止,因为你喜欢它们data()

std::vector<std::string> vector {
    "Futbol",
    "AUTOmata",
    "fUT",
    "auto"
};

Live demo现场演示


If you want to use C "features" on the other hand:另一方面,如果您想使用 C 的“功能”:

const int largo = 3;
char** vector = new char* [largo+1];
for (int i = 0; i < largo + 1; ++i)
    vector[i] = new char[10];
strcpy(vector[0], "Futbol");
strcpy(vector[0], "AUTOmata");
strcpy(vector[0], "fUT");
strcpy(vector[0], "auto");

Live demo现场演示

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

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