【问题标题】:How to access a row of a C++ char matrix?如何访问一行 C++ 字符矩阵?
【发布时间】:2019-02-05 11:14:47
【问题描述】:

经过多年的 matlab,我正在重新学习 C++。这是我写的一些代码

char  couts[3][20]={"Area of Rectangle: ","Area of Triangle: ","Area of Ellipse: "};
char C[20];
for (int i = 0; i < 3; i++) {
  C=couts[i];
  cout << C;
  //code that calculates and couts the area
}

显然,这是打印该行 couts 的错误方法,但在尝试了许多变化和谷歌搜索之后,我无法弄清楚我做错了什么。 :(

【问题讨论】:

  • 你需要strcpy(C, couts[i]);,但是当你使用C++时,你应该使用std::string,而不是使用旧的C函数,比如strcpy等。对于原始数组也是如此,使用相当标准的容器,例如std::arraystd::vector 等。
  • char* C; 可以让你做你想做的作业……但是为什么不直接输出呢? (std::cout &lt;&lt; couts[i];)
  • 如果你不想修改字符串:char const* const couts[3] = { ... }; char const* C;

标签: c++ arrays matrix char


【解决方案1】:

您可能应该使用 C++ 功能而不是旧的 C 习惯用法:

#include <iostream>
#include <array>
#include <string>

const std::array<std::string, 3> couts{ "Area of Rectangle: ","Area of Triangle: ","Area of Ellipse: " };

int main()
{  
  std::string C;
  for (int i = 0; i < couts.size(); i++) {
    C = couts[i];
    std::cout << C << "\n";
    //code that calculates and couts the area
  }
}

【讨论】:

  • 在 main 之外创建 const 有什么意义?
  • @Abijah 没有必要改变这个“数组”的元素
  • @Abijah 这是标准 C/C++。在 main 之外它是 一个全局 变量,在它里面是一个 local 变量,google ""c global vs local variables"" 以获取更多信息和/或在你的 C 中阅读它/C++ 教科书。
【解决方案2】:

在这种情况下使用strings 甚至string_views,而不是字符数组。您没有复制C 中的字符串,因此cout 不起作用。在现代 C++ (C++17) 中,这将是:

constexpr std::string_view couts[] = {"Area of Rectangle: ","Area of Triangle: ","Area of Ellipse: "};
std::string_view C;
for (auto s: couts) {
  std::cout << s << std::endl;
}

这可能是我唯一会编写 C 样式数组而不使用 std::array 的地方,因为将来元素的数量可能会发生变化。

【讨论】:

  • 我想说,string_view 非常适合这个问题。但是我建议你发布一个介绍这个类的链接,因为 OP 不太可能知道它。
  • ...它是 C++17,OP 可能没有。
  • 同意,添加了对 C++17 的提及。
【解决方案3】:

这是一个使用 C++17 deduction guides for std::array 结合 std::string_view 的版本,让您可以在 std::arraystd::string_views 上使用基于范围的 for 循环等。

#include <iostream>
#include <array>

constexpr std::array couts = {
    std::string_view{"Area of Rectangle: "},
    std::string_view{"Area of Triangle: "},
    std::string_view{"Area of Ellipse: "}
};

int main() {
    for(auto& C : couts) {
        for(auto ch : C) {
            std::cout << ch; // output one char at a time
        }
        std::cout << "\n";
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 2013-08-03
    • 2020-12-26
    • 2023-03-25
    • 2014-07-24
    • 2016-03-31
    相关资源
    最近更新 更多