这是我的代码:
#include<iostream>
#include<string.h>
#define SIZE 100
struct person{
std::string name;
int age;
};
void entry(struct person *info){
std::getline(std::cin, info->name);
std::cin >> info->age;
}
int main(int argc, char const *argv[]) {
struct person roster[SIZE];
int n; // number of people in the roster:
std::cin >> n;
for (int i = 0; i < n; i++){
entry(&roster[i]);
}
return 0;
}
我正在学习如何在 C++ 中使用“struct”,在这个程序中,我创建了一个包含姓名和年龄的名册,但是每当我尝试读取字符串“name”时程序就会崩溃。你能帮助我吗?谢谢,我坚持了好几天。
P.s:我正在用一本 C 书学习 C++,所以我的代码可能包含 C-ism。
答案 0 :(得分:0)
请不要介意我在这里介绍的用户打印。他们的执行流程更加清晰。
因此,您应该注意以下事项:
#include<iostream>
#include<string.h>
#define SIZE 100
struct person{
std::string name;
int age;
};
void entry(struct person *info){
std::cout << "Enter name: ";
std::getline(std::cin, info->name);
std::cout << "\nAge: ";
std::cin >> info->age;
std::cin.ignore();
std::cout << std::endl;
}
int main(int argc, char const *argv[]) {
person roster[SIZE];
int n; // number of people in the roster:
std::cout << "Number of people in roster: ";
std::cin >> n;
std::cin.ignore();
for (int i = 0; i < n; i++){
entry(&roster[i]);
}
}
示例:
Number of people in roster: 3
Enter name: Foo
Age: 22
Enter name: Bar
Age: 33
Enter name: Baz
Age: 44
您遇到的主要问题是复杂的,其根源在于 getline()
行为。我建议您查看此 thread 以获得更多详细说明。
对于什么是 std::cin.ignore()
,请检查 documentation。以及何时以及如何使用它,请查看此thread。
答案 1 :(得分:0)
在声明一个 struct
之后,要声明变量,您只需在声明一个 int
或 double
时执行相同的操作:
(struct) <struct_name> <variable_name> = <value>;
这就是 C 和 C++ 的不同之处。在 C++ 中,struct 关键字在变量声明之前是可选的。在 C 中,它是强制性的。这就是为什么
<块引用>我正在用一本 C 书学习 C++
是一个巨大的数字。虽然它们的一些语法相似,但其余的却大不相同。如果您正在学习 C++,请找到相应的课程/书籍/视频。它们很丰富。
对于 the getline()
problem,您可以包含 cin.ignore()
以便程序忽略该行的其余字符并转到新行。
#include<iostream>
#include<string.h>
#define SIZE 100
struct person{
std::string name;
int age;
};
void entry(person *info){
std::cin.ignore(); //ignores every character until next line
std::getline(std::cin, info->name);
std::cin >> info->age;
}
int main(int argc, char const *argv[])
{
person roster[SIZE];
int n; // number of people in the roster:
std::cin >> n;
for (int i = 0; i < n; i++)
{
entry(&roster[i]);
}
for (int i = 0; i < n; i++)
{
person cur = roster[i];
std::cout << cur.name << " " << cur.age << "\n";
}
return 0;
}
结果:
2
Beck
8
John Doe
25
Beck 8
John Doe 25