c++ - 将字符串放入链表
问题描述
我的字数统计功能有一些问题。如果有人可以请帮忙。我正在从输入文件中读取字符,将它们转换为单词。我将它们添加到链表并使用打印语句检查每个单词是否进入链表。当我在 wordcount 函数中调用 My printList 函数时,它只打印头部。显然 head->next 为空
typedef struct wordNode{
int data;
char *word;
struct wordNode *next;
}wordNode;
void wordCount(char *FileName); // function prototype
void printList(wordNode *head);
int main(int argc, char *argv[]){
int i,j;
int count = argc-1; // the count basically tells the for loop how many times to runs i.e number of files
pid_t childpid[count], wpid; // making a childpid array for forking more than one process
int status=0; // for parent process to wait for child
if(argc >= 1){
for(j=1; j<argc; j++){
childpid[j] = fork();
if(childpid[j] == -1)
printf("The fork didn't go through for process %d\n", j);
else if(childpid[j] == 0){
// printf("got here\n");
wordCount(argv[j]);
}
}
}
else {
printf("incorrect no. of argc\n"); }
//here the following code makes parent to wait for all the child processes to terminate
while((wpid = wait(&status)) > 0){
if ((wpid == -1)){
printf("Father didn't wait for child to term");
break;
}
}
printf("All %d files have been counted\n", count);
return 0;
}
void wordCount(char *FileName){
char prev; // keep track of last word that was read
char character;// to keep track of each character when reading input data
int words=0; // keep count of words
FILE* fp;
char thisword[100];
int k=0;
wordNode *head;
wordNode *current;
head=NULL;
current = NULL;
fp=fopen(FileName,"r");
prev='\0';
if(fp==NULL){
printf("unable to open the file\n");
exit(EXIT_FAILURE); }
else{
while((character = fgetc(fp)) != EOF ){
if(character == ' ' || character == '\t' || character=='\0' || character =='\n' ){
printf("in here\n");
words++;
thisword[k]='\0';
printf("HERE THE WORD is %s\n", thisword);
printf("\n");
if (head==NULL){
head = malloc(sizeof(wordNode));
head->next = malloc(sizeof(wordNode));
head->word = (char *)calloc(strlen(thisword) + 1, strlen(thisword));
strcpy(head->word, thisword);
printf("%s \n", head->word);
current = head->next;
}
else{
current = (wordNode*)malloc(sizeof(wordNode));
current->word = (char *)calloc(strlen(thisword) + 1, strlen(thisword));
strcpy(current->word, thisword);
current->next = NULL;
printf("%s\n ", current->word);
current = current->next;
}
k=0;
}
else {
thisword[k++] = tolower(character);
}
}
printList(head);
printf("Child process for %s: number of words is %d\n", FileName,words);
exit(0);
fclose(fp);
}
}
void printList(wordNode *head)
{
while(head != NULL)
{
printf("%s ", head->word);
head = head->next;
}
解决方案
推荐阅读
- php - 获取分类链接
- mysql - 如果没有匹配的行,则获取具有一个匹配条件的行或所有行
- jmeter - 如何从 JMeter 日志中断言标准输出语句?
- c++ - 我收到错误消息,我对类函数进行了未定义的引用
- azure-devops - 在 Azure Devops 中,查看特定状态下特定 sprint 的总故事点的最简单方法是什么
- python - 如何比较两个数据框之间每列下每一行的值?
- tensorflow - 使用 ZED 相机进行通用对象检测的最可靠/最简单的机器学习算法/技术是什么?
- python - Discords Bots 特定标签
- react-native - 如何在 React 组件之外写入 Redux 存储?
- python - 数据框列中的展平列表类型导致“浮动”对象不可迭代`类型错误