C++程序无法正常运行
C++ program doesn't run correctly
我写了一个笔记程序。它读取一些笔记,保存它们,并允许用户删除,选择或更新笔记。它正在编译和运行,但是不能正确运行。
我有这个结构体:
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
函数调用,那么您可能已经发现了这个错误。
相关文章:
- 运行程序时出现问题
- 分段错误当我试图运行程序时出错
- C++ 每次运行程序时我都会"nan"输出的问题
- 多线程程序卡在优化模式下,但在 -O0 中正常运行
- 如何制作硬编码堆栈,而不是硬编码并保持程序正常运行
- 我的程序运行良好,可以复制对象,但是当我使用复制分配(=)时,它仍然可以正常运行.为什么不给错误
- 在 Ubuntu 16.04 的 usr/local/bin 中安装的 c++ 应用程序在从主目录执行时无法正常运行
- 如何调试正常运行但在 ide 中返回分段错误的程序?
- 第一次运行程序时出现损坏的双链表错误,后续运行正常
- 当我尝试为我的程序提供 3 个输入时,它需要 4 个才能正常运行.为什么
- 程序无法在 dev C++ 上正常运行
- C++ 程序将无法正常运行
- 为什么这个程序在Clang或GCC下不能正常运行?
- For 循环结束自身并终止正在运行的程序,但在删除斜率计算语句时正常运行
- 读取元音并擦除元音的程序将无法正常运行
- 为什么这个简单的链表程序无法正常运行
- 使用sublime-build时不能运行c++程序,从终端运行时工作正常
- c ++程序无法在Mac上正常运行,但在Windows上可以
- c#包装到c++函数-运行一次,工作正常.运行两次,程序挂起
- C++程序无法正常运行