如何访问一个C ++的char矩阵的行?

问题描述 投票:0回答:3

我经过多年的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的该行打印的错误的方式,但在尝试许多变化和谷歌上搜索我不能工作后,我在做什么错。 :(

c++ arrays matrix char
3个回答
2
投票

你也许应该使用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
  }
}

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,作为元素的数量可能在未来改变。


2
投票

下面是一个使用C++17 deduction guides for std::arraystd::string_view让您使用基于for循环的std::arraystd::string_views都等范围相结合的版本。

#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";
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.