经过多年的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
}
很显然,这是打印那排母线的错误方法,但是尝试了许多变化并进行了谷歌搜索之后,我无法弄清我做错了什么。 :(
答案 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::array和std::string_view的版本,让您在std::array
和std::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";
}
}