我经过多年的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 ++的功能,而不是旧的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
}
}
在这种情况下,不是字符数组使用string
s甚至string_view
s。你是不是在复制的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
,作为元素的数量可能在未来改变。
下面是一个使用C++17 deduction guides for std::array与std::string_view让您使用基于for循环的std::array
和std::string_view
s都等范围相结合的版本。
#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";
}
}