无法使用fgets函数读取字符串

时间:2019-03-25 15:00:11

标签: c

我正在尝试接受多个输入(字符串,整数和双打)并将它们添加到链接列表中,但我无法获得fgets()函数正常工作,并且没有构造性错误可以帮助我找到解决方案

我要求用户分别输入每个详细信息,然后尝试将其添加到链接列表中。 我意识到scanf不起作用,因此尝试使用fgets,而且似乎也不起作用。

void add(){ 
  struct LinearNode *aNode;
    struct book *anElement;

    char *idB,*nameB,*authorB;
    int yearB,loanedTimesB;
    double valueB;

  anElement = (struct book *)malloc(sizeof(struct book));
  if (anElement == NULL)
            printf("Error - no space for the new element\n");
        else{
      printf("Please enter the book ID.\n");
      fgets(anElement->id,sizeof anElement->id,stdin);
      //strcpy(anElement->id, idB);
      printf("Please enter the name of the book.\n");
      scanf("%s", anElement->name);
      printf("Please enter the name of the book author.\n");
      scanf("%s", anElement->author);
      printf("Please enter the year of publication.\n");
      scanf("%d", &anElement->year);
      printf("Please enter the initial book value.\n");
      scanf("%lf", &anElement->value);
      anElement->loanedTimes = 0;
      anElement->loaned = false;

      aNode = (struct LinearNode *)malloc(sizeof(struct LinearNode));
      if (aNode == NULL)
                printf("Error - no space for the new node\n");
          else { // add data part to the node
                aNode->element = anElement;
                aNode->next = NULL;
                //add node to end of the list
                if (isEmpty()) {
                   front = aNode;
                   last = aNode;
                }
                else {
                     last->next = aNode;
                     last = aNode;
                  } //end else
           }
    }
}

这是完整的代码

#define _CRT_SECURE_NO_WARNINGS
#define bool int
#define false 0
#define true (!false)

//Libraries
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
//Preprocessor Variable
#define SIZE 10

struct book{
  char *id,*name,*author;
  int year,loanedTimes;
  bool loaned;
  double value;
};

struct LinearNode {
    struct book *element;
    struct LinearNode *next;
};

struct LinearNode *front = NULL;
struct LinearNode *last = NULL;

void check(),menu(),add(),borrow(),returnBook(),deleteBook(),viewAll(),viewOne(),viewPopNo(),viewValue();
bool isEmpty();
int main(int argc, char *argv[]) {
    check();
  menu();
    return 0;
}

void check(){
  if( access( "book.dat", F_OK ) != -1 ) {
    printf("The system has been populated with books from the data file.\n");
} else {
    printf("Database of books doesn't exist.\nPlease populate it using the first function from the menu.\n");
}
}

void menu(){
    int x = 0;
    do{
    printf("1. Add a new book to the library \n");
    printf("2. Allow customer to take out a book \n");
    printf("3. Allow Customer to return a book \n");
    printf("4. Delete an old book from stock \n");
    printf("5. View all books \n");
    printf("6. View a specific book \n");
    printf("7. View details of most popular and least popular books \n");
    printf("8. Check value of the books \n");
    printf("9. Exit the system \n");
  scanf("%d",&x);
  getchar();
  if (x==1)
  add();
    }while(x!=9);
}
void add(){ 
  struct LinearNode *aNode;
    struct book *anElement;

    char *idB,*nameB,*authorB;
    int yearB,loanedTimesB;
    double valueB;

  anElement = (struct book *)malloc(sizeof(struct book));
  if (anElement == NULL)
            printf("Error - no space for the new element\n");
        else{
      printf("Please enter the book ID.\n");
      fgets(anElement->id,sizeof anElement->id,stdin);
      //strcpy(anElement->id, idB);
      printf("Please enter the name of the book.\n");
      scanf("%s", anElement->name);
      printf("Please enter the name of the book author.\n");
      scanf("%s", anElement->author);
      printf("Please enter the year of publication.\n");
      scanf("%d", &anElement->year);
      printf("Please enter the initial book value.\n");
      scanf("%lf", &anElement->value);
      anElement->loanedTimes = 0;
      anElement->loaned = false;

      aNode = (struct LinearNode *)malloc(sizeof(struct LinearNode));
      if (aNode == NULL)
                printf("Error - no space for the new node\n");
          else { // add data part to the node
                aNode->element = anElement;
                aNode->next = NULL;
                //add node to end of the list
                if (isEmpty()) {
                   front = aNode;
                   last = aNode;
                }
                else {
                     last->next = aNode;
                     last = aNode;
                  } //end else
           }
    }
}
bool isEmpty() {
    if (front == NULL)
        return true;
    else
        return false;
}




1 个答案:

答案 0 :(得分:1)

#include <string> #include <iostream> #include <windows.h> #include <stdlib.h> using namespace std; struct Person { string name; string race; int weight; void write(); void show(); void check(); }; void Person::show() { cout<<"ÔÈÎ: "<<name<<endl; cout<<"Íîìåð ðåéñà: "<<race<<endl; cout<<"Âåñ áàãàæà: "<<weight<<endl; } void Person::write() { cout<<"Ââåäèòå ÔÈÎ: "; getline(cin,name); cout<<"Ââåäèòå íîìåð ðåéñà: "; getline(cin,race); cout<<"Ââåäèòå âåñ áàãàæà: "; cin>>weight; } int main() { Person* persons=new Person[4]; for (int i = 0; i < 4; i++) { persons[i] = new Person(); persons[i].write(); } for (int i = 0; i < 4; i++) { persons[i].show(); } cout<<"Ñ áàãàæîì áîëüøå 10 êã: ";//<<counter<<" ÷åëîâåê"<<endl; return 0; } 产生一个指针的大小!

sizeof anElement->id

您应该分配足够的空间并读取那么多字节

fgets(anElement->id,sizeof anElement->id,stdin);
//                  ^^^^^^^^^^^^^^^^^^^^
//                  size of a pointer
//                  probably 4 or 8

当您不再需要内存时,请不要忘记anElement->id = malloc(100); // error checking omitted for brevity fgets(anElement->id, 100, stdin); // error checking omitted for brevity // use anElement->id free(anElement->id);