我正在编写一个程序,要求我输入字符,并将其存储在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
但我收到一个错误消息。
答案 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_name
和last_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)
将<=
更改为<
。
否则它将超出内存限制