STL和数据从字符串到向量

STL and data from string to Vector

本文关键字:向量 字符串 数据 STL      更新时间:2023-10-16

好的,我已经试过了。我有下面的类,我有一个驱动程序,它将读取一个文件,并使用getline获取所有内容,并将其复制为字符串。

在我的驱动程序中,我也有vector<Seminar>

我感到困惑的是如何把我的数据从字符串到向量。现在我在想,也许首先我需要创建一个构造函数等等,让它工作?

我似乎不能正确地实现它。

class Seminar
{
    public:
        Seminar(int number = 0, string date = "yyyy-mm-dd" , string title = "")
        {
          Number = number;
          Date = date;
          Title = title;
        }
        int get_number() const {return Number; }
        string get_date() const {return Date; }
        string get_title() const {return Title; }
    private:
        int Number;     // Seminar number
        string Date;      // Date of Seminar
        string Title;   // Title of Seminar
};


enter code here 
    vector<Seminar> all;
    main()
ifstream InFile;
string Letter;
string File;
cout << "Type Letter from the Menu: "<<endl;
cin >> Letter;
if (Letter == "A" || "a")
{
    cout << "What is the file you would like to read: "<<endl;
    cin >> File;
    InFile.open(File.c_str(),ios::in);
    if(InFile)
    {
        string line = "";
        while(getline(InFile,line))
        {
            cout << line << endl;
        }
    InFile.close();
    }
}`enter code here`

下面的内容应该指向正确的方向:

#include<vector>
#include<iostream> 
#include<string>
int main()
{
  std::vector<std::string> myStringVector;
  myStringVector.push_back("First");
  myStringVector.push_back("Second");
  std::cout<<myStringVector[0]<<"n"<<myStringVector[1]<<"n";
  return 0;
 }

我想你可能需要这样做:

Seminar seminar1(<data here>);
std::vector<Seminar> seminarVector;
seminarVector.push_back(seminar1);

如果您有一个vector,则使用push_back()向其添加值。

std::vector<std::string> foo;
foo.push_back( "hi there!" );