我试图这样做,如果userselection = 1,则会询问用户问题以创建地址簿的联系人。它将所有联系人信息保存到结构中,然后保存到.txt文件。我是C ++的新手。这就是我到目前为止......我一直在'。'之前得到 [Error]期望的primary-expression。令牌。< ----我如何修复此问题 此外,任何人都可以提供如何将结构保存到文件的指导? 感谢。
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
struct person{
string Name;
string Address;
string PhoneNumber;
string Email;
};
int main(){
int userselection = 0;
cout << "What do you want to do? Press 1 to Add Contact -- Press 2 to Search for Contact"<<endl;
cin >> userselection;
if(userselection == '1');
person newPerson;
cout << "What is your Name?" << endl;
cin >> person.Name;
cout << "What is your Address?" << endl;
cin >> person.Address;
cout << "What is your Phone Number?" << endl;
cin >> person.PhoneNumber;
cout << "What is your Email?" << endl;
cin >> person.Email;
}
答案 0 :(得分:4)
对于您描述的错误,您需要访问类实例中的成员,而不是类定义..
newPerson.Name
而不是
person.Name
答案 1 :(得分:2)
您的错误只与语法有关。请在将来阅读编译器的错误消息。
#include <iostream>
#include <string> // added
using namespace std;
struct person {
string Name;
string Address;
string PhoneNumber;
string Email;
};
int main() {
int userselection = 0;
cout << "What do you want to do? Press 1 to Add Contact -- Press 2 to Search for Contact"<<endl;
cin >> userselection;
if(userselection == 1) { // userselection is int so why compare it to char
person newPerson;
cout << "What is your Name?" << endl;
cin >> newPerson.Name; // assign to object's member not a static member
cout << "What is your Address?" << endl;
cin >> newPerson.Address;
cout << "What is your Phone Number?" << endl;
cin >> newPerson.PhoneNumber;
cout << "What is your Email?" << endl;
cin >> newPerson.Email;
}
}