比较c++中链表中的两个字符串
comparing two strings from linked list in c++
所以我在需要的地方有这个赋值1-从341行的文本文件中读取2-列出341人的姓名(前30个字符)3-一些名称是重复的
因此,我想做的是在创建它时,在将其链接到列表之前,检查名称是否已经包括在内。
在做了一些测试后,我意识到我正在比较的两个字符串都作为列表的第一个名称打印出来,并且似乎忽略了列表的其余部分。当我删除对布尔函数的调用时,列表会打印出来。
我是一个学生,又是一个不祥的开始,所以我担心我可能会错过几步?感谢任何帮助或指导!!谢谢
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cerrno>
using namespace std;
struct Pays
{
char nom[20+1]; /* nom du pays */
Pays *suivant; /* pointeur sur le prochain pays */
} ;
struct Emploi
{
char nom[29+1]; /* nom de l’emploi */
Emploi *suivant; /* pointeur sur le prochain emploi */
} ;
struct Espion
{
std:: string nom; /* nom de l’espion(ne) */
Pays *listePays; /* tête de liste des pays visités */
Emploi *listeEmploi; /* tête de liste des emplois occupés */
Espion *suivant; /* pointeur sur le prochain espion */
} ;
bool trouverNomListe(Espion* ptr, std ::string nomAChercher)// returns true if the name is already on the list
{
if(ptr->suivant == NULL)
return false;
else
if(ptr->nom.compare(nomAChercher) == 0){
std:: cout<< ptr->nom << std::endl;// checking if the function is comparing the strings
return true;
}
else
trouverNomListe(ptr->suivant, nomAChercher); //keeps looking thru the list
}
int main()
{
const int MAX_NOM = 30, MAX_PAYS = 20, MAX_EMPLOI = 29;
char nomFichier[50] = "espion.txt";
int n = 0;
std:: string infoEspion;
Espion *actu = NULL;
Espion *debut = NULL;
Espion *fin = NULL;
Espion *nouveau = NULL;
std :: ifstream aLire;
aLire.open(nomFichier, std::ios::in);
if(!aLire.is_open()){
exit(EXIT_FAILURE);
}
while(std::getline(aLire, infoEspion))
{
if(debut == NULL){// if the list is empty
nouveau = new Espion;
nouveau -> nom = infoEspion.substr(0,30);
nouveau -> suivant = NULL;
debut = nouveau;
actu = nouveau;
fin = nouveau;
std::cout << actu -> nom<< std::endl;
}
else
if(trouverNomListe(debut, infoEspion.substr(0,30)) == false )
{
nouveau = new Espion;
nouveau -> nom = infoEspion.substr(0,30);
nouveau -> suivant = NULL;
actu -> suivant = nouveau;
fin = nouveau;
actu = nouveau;
std::cout << actu -> nom<< std::endl;
}
}
aLire.close();
system("pause");
return 0;
}
您的trouverNomListe
函数是递归的,这是不正确的。它应该简单地按顺序浏览列表,例如
bool trouverNomListe(Espion* ptr, std ::string nomAChercher)// returns true if the name is already on the list
{
while (ptr)
{
if(ptr->nom.compare(nomAChercher) == 0)
return true;
ptr = ptr->suivant;
}
return false;
}
您的代码还有其他几个问题,但这似乎是主要问题。
相关文章:
- 两个字符串在 c++ 中不相等
- 在C++的两个字符串中连接以逗号分隔的唯一值
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 比较两个字符串后卡在无限循环中
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 我需要帮助在一个类中输入两个字符串并获取其输出
- 两个字符串之间的数学运算
- sscanf() 有两个字符串参数
- 我的字符串数组一次打印出前两个字符串
- 两个 c++ 字符串上的异或
- 函数返回两个字符串的第一个常用字符
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)
- 我需要在C++的两个字符串之间找到共同的前缀
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 给定两个字符串 S 和 T.确定与 T 相差最小的 S 子字符串?
- gtest:检查字符串是否等于两个字符串之一
- 交换两个字符串时访问正确的内存时,我遇到了分段错误
- 我可以在系统()中使用两个字符串吗?