我在理解如何从程序中获取用户输入并将其传递到函数AddNumber
时遇到了麻烦。该程序将启动并要求用户输入并将其存储到输入数组中,但是我不确定如何从数组中获取信息并将其传递给函数AddNumber
。
我已经了解到我的“ AddNumber”功能没有执行任何操作,因此我已经更新了代码。我的印象是我创建了指针“ previous”,而previous = NULL?
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
typedef struct A_NewNumber {
struct A_NewNumber *next;
char newNum;
} NewNumber;
NewNumber *AddNumber(NewNumber *previous, char *input){
//char input[16];
//double numEntered = 0;
NewNumber *newNum = malloc(sizeof(NewNumber));
sscanf(input, "%lf", &newNum->newNum);
//sscanf(input, "%s", newNum->enterNumber);
//numEntered = atof(input);
//possible code
/*if (previous != NULL){
previous->newNum;
}
newNum->next = NULL;
newNum->newNum = 0;
return newNum;
}*/
void PrintList(NewNumber *numStart) {
NewNumber *currentNumber = numStart;
int count = 0;
while (currentNumber != NULL) {
count++;
printf("Number Position:%s\n", currentNumber->enterNumber);
currentNumber = currentNumber->next;
}
printf("Total Numbers Entered%d\n", count);
}
void CleanUp(NewNumber *start) {
NewNumber *freeMe = start;
NewNumber *holdMe = NULL;
while (freeMe != NULL) {
holdMe = freeMe->next;
free(freeMe);
freeMe = holdMe;
}
}
int main(){
//indexNum = 0;
char command[16];
char input[16];
//float userInput;
NewNumber *userEnter = NULL;
NewNumber *start = NULL;
NewNumber *newest = NULL;
while(fgets(input, sizeof input, stdin)){
printf("Please enter a number->");
printf("Enter 'quit' to stop or 'print' to print/calculate");
sscanf(input, "%s", command);
if(newest == NULL){
start = AddNumber(NULL, input);
newest = start;
}else{
newest = AddNumber(newest, input);
}
if( strncmp(command, "print", 5) == 0){
PrintList(start);
}else if( strncmp(command, "quit", 4)== 0){
printf("\n\nQuitting....\n");
break;
//userInput = enterNumber;
}
}
CleanUp(start);
return 0;
}
最佳答案
在不对代码进行过多修改的情况下,我建议AddNumber采用指向先前的NewNumber以及用户输入的指针。您的意图似乎也是读取double
,因此我将newNum字段修改为double
类型。像这样:
typedef struct A_NewNumber{
struct A_NewNumber *next;
double newNum;
} NewNumber;
NewNumber *AddNumber(NewNumber *previous, char *input){
NewNumber *newNum = malloc(sizeof(NewNumber));
/* use %lf to read in a double */
sscanf(input, "%lf", &newNum->newNum);
if (previous != NULL){
previous->next = newNum;
}
return newNum;
}
然后,当您调用AddNumber函数时,您可以传递前一个和输入
if(newest == NULL){
start = AddNumber(NULL, input);
newest = start;
} else {
newest = AddNumber(newest, input);
}
关于c - AddNumber功能故障,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39421127/