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

时间:2019-02-05 11:14:47

标签: c++ arrays matrix char

经过多年的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
}

很显然,这是打印那排母线的错误方法,但是尝试了许多变化并进行了谷歌搜索之后,我无法弄清我做错了什么。 :(

3 个答案:

答案 0 :(得分:2)

在这种情况下,请使用string甚至string_view,而不要使用char数组。您没有在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的地方,因为将来元素的数量可能会改变。

答案 1 :(得分: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 :(得分:2)

这是结合使用C++17 deduction guides for std::arraystd::string_view的版本,让您在std::arraystd::string_view上都使用基于范围的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";
    }
}