[英]Reading a text file into a vector from the command line
Whenever I try to see the contents inside the vector I get "segmentation fault" any idea why that is? 每当我尝试查看向量中的内容时,都会收到“分段错误”的提示,这是为什么呢? Do I not read in the values properly?
我不能正确读取值吗?
#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;
}
the text file contains these numbers: 文本文件包含以下数字:
5 6 7 11 12 13
A vector doesn't automatically come with slots. 向量不会自动带有插槽。 You have to either
reserve
slots or use push_back
to append items to the vector
: 您必须
reserve
插槽或使用push_back
将项目附加到vector
:
//...
int value;
in >> value;
list.push_back(value);
Read what's in the file using getline. 使用getline读取文件中的内容。 See sample code below:
请参见下面的示例代码:
ifstream InFile(argv[1], ios::in); /*Open file from arg[1]*/ std::string LineContent; getline(InFile, LineContent); /*Save line per line */
With your line saved in a string, you can now transfer the data from that string to the vector, see: 将行保存在字符串中后,您现在可以将数据从该字符串传输到向量,请参见:
vector<int> list; list.push_back(atoi(LineContent.c_str()));
Now, you can print out what's in the file: 现在,您可以打印出文件中的内容:
for (int i = 0; i < list.size(); i++) cout << list[i] << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.