c++ - 为什么以下 C++ 代码会为此特定输入提供分段错误?
问题描述
int main(){
int n;
cin>>n
cin.ignore(32767,'\n');
string arr[n],temp;
for(int i=0;i<n;i++){
getline(cin,temp);
arr[i]=temp;
}
}
输入:
10 个
旅游
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
订户
rowdark
tankengineer
我的代码对于所有其他输入(即使 n = 10)运行良好,但对于这个特定输入(如上所述),它给出了分段错误。
解决方案
您的代码可能无法按原样编译,并且您使用的是 C++ 不支持的VLA:s,因此很难重现您的问题。尝试通过使用 C++ 容器(如 a std::vector
)来避免它。例子:
#include <iostream>
#include <vector>
int main() {
int n;
std::cin >> n;
std::cin.ignore(); // discard the '\n' still in the buffer
// declare a standard C++ container, like a vector of strings
std::vector<std::string> arr(n);
for(int i=0; i<n; ++i) {
std::getline(std::cin, arr[i]);
}
std::cout << "VALUES:\n";
for(auto& s : arr) {
std::cout << s << "\n";
}
}
推荐阅读
- android - 有没有办法只在 Android 中使用 GoogleMaps API 来收听平底锅?
- r - 在模块中使用 addPopover
- google-analytics - BigQuery:基于最近的时间戳加入
- android - 重载的 dispatchKeyEvent 方法在其中添加一些后处理代码时冻结应用程序
- docker - 复制名为“run”的文件后出现 Docker 错误
- java - 拿第一项不完成
- linux-kernel - 启动 Linux 的最低处理器能力
- c++ - 共享库依赖的CMAKE RPATH问题
- python-3.x - 如何将除法运算符 / 分配给文本单词“divided”或“divides”
- ruby - 带有标签的 rspec 过滤器 - 不要在 `describe` 中运行代码