[英]can't make strstr() work
我有一项杂务工作,我无法完全在一个区域中正常工作,特别是在我尝试比较字符串的地方。 这是作业:
您将编写一个程序来提示用户输入学生姓名,年龄,gpa和毕业日期。 然后,您的程序将读取所有学生信息,并将其存储到链接列表中。 然后,程序将打印学生的姓名。 接下来,程序将提示用户输入字符串。 该程序将为每个学生打印完整的信息,其中包括姓名中的字符串。
这是我所拥有的:
#include <iostream>
#include <cstring>
using namespace std;
const char NAME_SIZE = 50;
struct StudentInfo
{
char studentName[NAME_SIZE];
int age;
double gpa;
char graduationSemester[3];
StudentInfo *next;
};
void displayStudentNames(StudentInfo *top);
void displayStudentInfo(StudentInfo *top);
int main(){
StudentInfo *top = 0;
cout << "Please enter the students. Enter the name, age, gpa, and semester of graduation (e.g. F13)." << endl;
cout << "Enter an empty name to stop." << endl << endl;
bool done = false;
while(!done){
char nameBuffer[NAME_SIZE];
char graduationBuffer[3];
cin.getline(nameBuffer, NAME_SIZE);
if(nameBuffer[0] != 0){
StudentInfo *temp = new StudentInfo;
strcpy(temp->studentName, nameBuffer);
cin >> temp->age;
cin >> temp->gpa;
cin.getline(graduationBuffer, 3);
strcpy(temp->graduationSemester, graduationBuffer);
cin.ignore(80, '\n');
temp->next = top;
top = temp;
}else{
displayStudentNames(top);
displayStudentInfo(top);
done = true;
}
}
}
void displayStudentNames(StudentInfo *top){
cout << "Here are the students that you entered: " << endl << endl;
while(top){
cout << top->studentName << endl;
top = top->next;
}
cout << endl;
}
void displayStudentInfo(StudentInfo *top){
char name[NAME_SIZE];
do{
cout << "Which students do you want? ";
cin.getline(name, NAME_SIZE);
const char *str = top->studentName;
const char *substr = name;
const char *index = str;
while((index = strstr(index,substr)) != NULL){
cout << "Name: " << top->studentName << ", Age: " << top->age << ", GPA: " << top->gpa << ", Graduations Date: " << top->graduationSemester;
index++;
}
}while(name[0] != 0);
}
我的问题出在displayStudentInfo函数中,我只是无法使其正常工作。 我已经尝试了许多不同的方法,这只是我尝试过的最新方法。 但是在程序中较早地创建了链表之后,我们应该输入一个从字母到全名的字符串,并在列表中的任何位置找到它,然后打印出该特定名称的信息。
eta:我的链表向后存储结构时也遇到问题? 它也可能不存储我的毕业日期,或者当我尝试打印日期时出了点问题,因为它们打印为空白。
您的代码问题很明显。 您只是在检查列表的头,而不是遍历列表。
这是有问题的部分(假设每个函数调用应返回一位学生的信息):
void displayStudentInfo(StudentInfo *top){
char name[NAME_SIZE];
//Addes 'node' variable for simplicity, you can use 'top' itself
StudentInfo *node = top;
cout << "Which students do you want? ";
cin.getline(name, NAME_SIZE);
do{
// Check if name is correct
// "Entered name should be at start of field"
// You should use == not =
if(node->studentName == strstr(node->studentName, name){
cout << "Name: " << top->studentName << ", Age: " << top->age << ", GPA: " << top->gpa << ", Graduations Date: " << top->graduationSemester;
}
// Traverse in list
node = node->next;
// Until reach end of list
}while(node != NULL);
}
您需要在displayStudentInfo
内的某处添加top = top->next
,类似于在displayStudentNames
。 当前,如果没有此循环,您的循环将不会遍历链接列表。
我不会发布任何代码来避免您做作业,但是请随时向我提出更多问题或进行澄清。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.