每当我尝试查看 vector 中的内容时,我都会收到“段错误”,知道这是为什么吗?我没有正确读入这些值吗?
#include <iostream>
#include <cstdlib> // atoi function
#include <vector>
#include <fstream>
using namespace std;
vector<int> list ; // global vector
int main (int args , char * argv[])
{
ifstream in(argv[1]);
//ofstream out(argv[2]);
int listSize = atoi (argv[2]);
cout << listSize << endl;
int i = 0;
cout << argv[1] << endl;
in.open(argv[1]);
while (i < listSize)
{
in >> list[i];
cout << "test2" << endl;
i++;
}
in.close();
for( int k=0; k <listSize; k++){
cout<< list[k] << endl;
}
return 0;
}
文本文件包含这些数字:
5 6 7 11 12 13
最佳答案
vector 不会自动带有插槽。您必须 reserve
插槽或使用 push_back
将项目附加到 vector
:
//...
int value;
in >> value;
list.push_back(value);
关于c++ - 从命令行将文本文件读入 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51451737/