[英]Segmentation Fault while accepting input
我正在尝试接受来自用户的输入,其中第一行将是 Integer 以指示测试用例的数量
如果数字是 3
输入会像
3
Hello world
hey there, I am John
have a nice day
我正在使用getline
读取输入
我的代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int n;
cin >> n;
vector<string> arr;
for(int i=0; i<n; i++){
string s;
getline(cin, s);
arr[i] = s;
}
}
错误:
3
Segmentation fault(core dumped)
arr
是一个空向量,所以arr[i] = s;
将访问越界。 []
运算符不会增大向量。 它只能用于访问已经存在的元素。
不能使用[]
索引运算符创建向量的元素; 你的行arr[i] = s;
正试图将一个字符串分配给一个不(还)存在的元素。
有几种方法可以解决这个问题:首先,您可以使用push_back
函数在每个循环中向向量的末尾添加一个新元素; 其次,您可以使用resize
成员预先分配指定数量的元素(然后您可以在arr[i] = s;
行中使用); 第三个——也许是最简单的——你可以通过在声明(构造函数)中指定元素的数量来“预分配”向量的元素,如下所示:
#include <iostream>
#include <vector>
#include <algorithm>
#include <string> // Need this for the "getline()" function definition
using namespace std;
int main()
{
size_t n; // Indexes and operations on std::vector use "size_t" rather than "int"
cin >> n;
cin.ignore(1); // Without this, there will be a leftover newline in the "cin" stream
// std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // More precise, actually!
vector<string> arr(n);
// arr.resize(n); // Alternative to using 'n' in constructor
for (size_t i = 0; i < n; i++) {
string s;
getline(cin, s);
arr[i] = s;
}
for (auto s : arr) cout << s << endl; // Just to confirm the input values
return 0;
}
您的代码中还有一些其他问题,我已经“修复”并在我发布的代码中进行了评论。 随时要求进一步澄清和/或解释。
编辑:关于cin.ignore(1);
我添加的行,请参阅为什么 std::getline() 在格式化提取后跳过输入? (以及那里给出的优秀答案)了解更多详情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.