如何在结构中的向量中输入字符?

时间:2019-05-23 20:38:30

标签: c++ string struct stdvector

我正在编写一个程序,要求我输入字符,并将其存储在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

但我收到一个错误消息。

3 个答案:

答案 0 :(得分:3)

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

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

话虽这么说,std::vector<std::string>first_name没有意义。 std::vector<char>更有意义(就像您对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;
}

答案 1 :(得分:2)

这是问题所在

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

<=包含大小,该大小超出范围。使用<!=

答案 2 :(得分:0)

<=更改为<

否则它将超出内存限制