简体   繁体   English

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

[英]How to access a row of a C++ char matrix?

I am relearning C++ after many years of matlab. 经过多年的Matlab学习,我正在学习C ++。 Here is some code that I wrote 这是我写的一些代码

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
}

clearly this is the wrong way of getting that row of couts to print, but after trying many variations and googling I can't work out what I'm doing wrong. 显然,这是打印那排cout的错误方法,但是在尝试了多种变体和谷歌搜索之后,我无法弄清我做错了什么。 :( :(

Use string s or even string_view s in this case, not char arrays. 在这种情况下,请使用string甚至string_view ,而不要使用char数组。 You are not copying the string in C , so the cout doesn't work. 您没有在C复制字符串,因此cout不起作用。 In modern C++ (C++17), this would be instead: 在现代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;
}

This probably the only place I would write a C-style array and not use std::array , as the number of elements may change in the future. 这可能是我编写C样式数组而不使用std::array的唯一位置,因为将来元素的数量可能会更改。

You probbaly should use C++ features and not old C idioms: 您可能应该使用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
  }
}

Here's a version using the C++17 deduction guides for std::array combined with std::string_view letting you use range based for-loops etc. on both the std::array and the std::string_view s. 这是一个使用std :: arraystd :: string_view结合的C ++ 17演绎指南的版本, 让您在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";
    }
}

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

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