使用字符串库,我试图允许用户输入一些符号行,稍后将对其进行翻转。对我来说,最明显的方法似乎是使用字符串数组,但是,尽管我相信我的输入系统是正确的,但我的输出始终是大量的随机符号字符串,最终导致“ Abort”。我要做什么是不可能的?如果是这样,为什么(如果不是这样),我将如何解决该错误?
#include <iostream>
#include <string>
using namespace std;
/* Function Declarations */
string flipHouse();
int main() {
string flipped = flipHouse();
cout<<flipped;
return 0;
}
string flipHouse() {
int n;
cout<<"Enter the number of lines: ";
cin>>n;
string house[n];
cout<<"Enter the house image:"<<endl;
for (int i = 0; i < n+1; i++)
getline(cin,house,'\n');
for (int i = 0; i < n+1; i++)
cout<<house[i];
return house[n];
}
答案 0 :(得分:0)
string house[n];
此数组包含n
个字符串。有效索引为0 ... n-1。未定义访问数组的行为。
for (int i = 0; i < n+1; i++) cout<<house[i];
在最后几次迭代中,您访问的索引最多为n。该索引比数组的末尾大一号。
return house[n];
此处返回索引n中的字符串。再次超过最后一个索引。该程序的行为是不确定的。
另一个问题是n
不是编译时间常数值。因此,它不能用作C ++中数组的大小。