【问题标题】:How to enter characters to a vector in a structure?如何将字符输入到结构中的向量中?
【发布时间】:2019-05-23 20:38:29
【问题描述】:

我正在制作一个要求我输入字符的程序,我想将其存储在 vector 中声明的 struct 中。

我尝试使用char 类型和string 类型的新变量输入字符,但两者都不起作用。它在打印时给了我SIGSEGV 错误。

struct Student {
  int age, standard;
  vector<string> first_name;
  vector<char> last_name;
};

int main() {
  Student st;

  string k;

  cin >> st.age;
  getline(cin, k);

  st.first_name.push_back(k);

  cout << st.age << " " << endl;
  cout << "\t" << st.first_name.size() << endl;
  for (unsigned int x = 0; x <= st.first_name.size(); x++) {
    cout << st.first_name[x] << " ";
  }
}

当输入为:

11 lwpxiteeppsacowpnbxluqpmasgnwefzcsvrjxxammuqcftzgn

预期的输出是

11 lwpxiteeppsacowpnbxluqpmasgnwefzcsvrjxxammuqcftzgn

但我得到了一个错误。

【问题讨论】:

  • 为什么是vector&lt;char&gt; last_name;?而不仅仅是std::string last_name;?
  • 我可以看到vector 的名字,但是当你有很多名字时,只有一个可以是第一个。

标签: c++ string struct stdvector


【解决方案1】:

您的for 循环超出范围。您需要使用&lt; 而不是&lt;=

for(vector<string>::size_type x = 0; x < st.first_name.size(); ++x) {
    cout << st.first_name[x] << " ";
}

话虽如此,std::vector&lt;std::string&gt;first_name 没有意义。 std::vector&lt;char&gt; 会更有意义(就像您对 last_name 所做的那样),尽管使用 std::string 会更好:

struct Student {
    int age,standard;
    //char first_name[51],last_name[51];
    string first_name, last_name;
};


int main() {
    Student st;

    string k;

    cin >> st.age;// >> st.last_name >> st.standard;
    getline(cin, k);

    st.first_name = k;

    cout << st.age << " " << endl;// << st.first_name << " ";// << st.last_name << " " << st.standard;
    cout << "\t" << st.first_name << endl;
}

或者,由于您使用std::getline() 来读取全名,因此根本不要将first_namelast_name 分开:

struct Student {
    int age,standard;
    //char first_name[51],last_name[51];
    string name;
};


int main() {
    Student st;

    string k;

    cin >> st.age;// >> st.last_name >> st.standard;
    getline(cin, k);

    st.name = k;

    cout << st.age << " " << endl;// << st.first_name << " ";// << st.last_name << " " << st.standard;
    cout << "\t" << st.name << endl;
}

【讨论】:

    【解决方案2】:

    这就是问题所在:

    for (unsigned int x = 0; x <= st.first_name.size(); x++)
    

    &lt;= 包含超出范围的大小。使用&lt;!=

    【讨论】:

      【解决方案3】:

      &lt;= 更改为&lt;

      否则会内存不足

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-27
        • 2019-12-08
        相关资源
        最近更新 更多