如何将文本文件存储到向量中(C ++)

时间:2017-07-22 19:27:17

标签: c++ file vector

我需要帮助将文本文件中的文本存储到矢量中。

文本文件名为" names.txt"它有以下数据

salman
mahmoud
ahmad
ghadeer
raghad
abdullah
faisal

下面的文字是我的代码

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main ()
{
    vector<string> STRING;
    ifstream infile;

    infile.open ("names.txt");

    for(size_t i = 0; i < 7; i++)
    {
        getline (infile, STRING[i]);
        cout << STRING[i];
    }

    infile.close();

    return 0;
}

每次运行程序时,都会收到以下错误消息

Visual Studio Error Message

4 个答案:

答案 0 :(得分:3)

你声明了你的矢量,但你没有设置它的大小。

你可以:

  • 声明具有特定大小的矢量
  • 或简单地使用push_back()功能,如下所示:

for(size_t i = 0; i < 7; i++)
{
    string temp; // temporal variable - just a place holder
    getline (infile, temp); // get line 
    MyVector.push_back(temp); // add it to the vector (add to the end of it)
}

答案 1 :(得分:0)

您正在尝试访问未创建的向量元素。 当你打电话

vector<string> STRING

它创建了一个能够存储字符串但不具有任何字符串的向量。 因此,当您尝试使用STRING [i]访问其中一个时,它表示您正在尝试访问不存在的元素。

可能的解决方案:在循环调用之前

STRING.resize(7);

它将为7个空字符串分配内存,然后这个循环就可以了。

答案 2 :(得分:0)

您可以尝试这种方式:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main ()
{
    vector<string> STR;
    ifstream infile;

    infile.open ("names.txt");

    for(size_t i = 0; i < 7; i++)
    {
        string st;
        getline (infile, st);
        STR.push_back(st);
        cout << STR[i] << endl;
    }

    infile.close();

    return 0;
}

答案 3 :(得分:0)

您的问题是您正在尝试写入空向量。只需更改即可轻松解决此问题:

vector<string> STRING;

为:

vector<string> STRING(7);

但是,您应该将矢量名称更改为:

vector<string> lines;

最后一件事(不太重要)是你从文件中读取7行。如果文件有4行或56行怎么办?那么,这就是你应该做的事情:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main () {

   std::vector<std::string> lines;
   std::ifstream infile("names.txt");

   std::string line;
   while(std::getline(infile, line)) {
      lines.push_back(line);
      std::cout << lines.back() << std::endl;
   }

   return 0;
}