C++程序无法正常运行

C++ program doesn't run correctly

本文关键字:正常运行 程序 C++      更新时间:2023-10-16

我写了一个笔记程序。它读取一些笔记,保存它们,并允许用户删除,选择或更新笔记。它正在编译和运行,但是不能正确运行。

我有这个结构体:

struct List {
    char title[101];
    char text[501];
    int cont;
    struct List* next;
};typedef List list;

这些函数:

List* insert (List *l, char ti[101], char te[501]) {
    List* new = (List*) malloc(sizeof(List));
    strcpy (new -> title, ti);
    strcpy (new -> text, te);
    new -> next = l;
    new -> cont = id;
    id++;
    return (new);
}
List* delete (List* l, int v) {
   List *ant = NULL;
   List *p = l;
   while (p != NULL && p -> cont != v) {
      ant = p;
      p = p -> next;
   }
   if (p == NULL)
      return l;
   if (ant == NULL)
      l = p -> next;
   else
        ant -> next = p -> next;
   free(p);
   return l;
}
void print (List *l) {
    List *p;
    for (p = l; p != NULL; p = p -> next){
      cout << "nTitle: " << p -> title << "n";
      cout << "Text: " << p -> text <<  "n";
      cout << "Code: " << p -> cont << "n" << "n";
    }
}

int main上,我已经插入和打印了几次,它工作得很好。但是当我想删除一个笔记时,它不会删除,也不会得到一个错误代码。昨天它工作得很好,但是今天当我测试它的时候,什么都不行。我不明白为什么它一直在工作,现在它停了。

按照要求,主程序:

List* ini(){
    return (NULL);
}

int main() {
        List *l;
        char title[101];
        char text[501];
        char v;
        List* L1 = ini();
        cout << "nTitle: ";
        gets(title);
        cout << "Text: ";
        gets(text);
        L1 = insert (L1,title,text);
        fflush(stdin);
        cout << "nTitle: ";
        gets(title);
        cout << "Text: ";
        gets(text);
        L1 = insert (L1,title,text);
        fflush(stdin);
        cout << "nTitle: ";
        gets(title);
        cout << "Text: ";
        gets(text);
        L1 = insert (L1,title,text);
        print(L1);
        cout << "Delete: ";
        cin >> v;
        L1 = delete(L1, v);
        print(L1);
        return(0);
        }

注意:我重写了你的代码,不做翻译,所以现在delete是一个有效的函数称为deleteItem

你的当务之急是:

char v;
//...
cin >> v;
L1 = deleteItem(L1, v);  // <-- v is a char, 

,

List* deleteItem (List* l, int v) {

当你应该传递一个int时,你正在传递一个char变量给deleteItem。Change type of v to int .

发生的事情是你的char被转换成int型。因此,如果您输入1,它将被发送为49,因为1的ASCII值是49。

c++允许你做的一件事就是在变量的使用点附近声明变量。如果您声明的v更接近deleteItem函数调用,那么您可能已经发现了这个错误。