#include<bits/stdc++.h> using namespace std; typedef struct node{ char id[11]; char name[11]; int age; node *next; } *List; List InitList(List &head, int length) { head = new node; head->next = NULL; struct node *p; int t; while(length) { p = new node; cin>>p->id; cin>>p->name; cin>>p->age; cin.ignore(); p->next = head->next; head->next = p; length--; } return head; } node *GetElem(List &head,int i){ List p; p = head->next; int j = 1; if(i == 0) return head; if(i < 0) return NULL; while(p&&j<i) { p = p->next; j++; } return p; } List InsertList(List &head, int i) { struct node *p, *s; p = GetElem(head, i); s = new node; cin>>s->id; cin>>s->name; cin>>s->age; cin.ignore(); s->next = p->next; p->next = s; return head; } List DeleteList(List &head) { struct node *p, *pre; char id1[11]; cin >> id1; cin.ignore(); p = head->next; pre = head; while (p) { if (strcmp(p->id, id1) == 0) { pre->next = p->next; delete p; p = pre->next; } else { pre = p; p = p->next; } } } void PrintList(List &head) { struct node *p; p = head->next; while(p){ cout<<p->id<<" "<<p->name<<" "<<p->age<<" "<<endl;; p = p->next; } } int main() { int T; int n; int m; cin>>T; for(int i = 0;i<T;i++) { cin>>n; List head; InitList(head, n); PrintList(head); cin>>m; InsertList(head, m); PrintList(head); DeleteList(head); PrintList(head); if(i<T-1) cout<<endl; } }最后还是多一个回车,咋回事啊
时间: 2024-04-10 07:33:40 浏览: 78
万能头文件#include&amp;lt;bits/stdc++.h&amp;gt; using namespace std;
这段代码中的多余回车是因为在循环结束后,程序会继续读取下一个输入,而下一个输入是一个空行,因此会输出一个多余的回车。
为了解决这个问题,你可以在循环结束后添加一行代码 `cin.ignore()`,来忽略掉下一个输入的空行。修改后的代码如下:
```cpp
int main()
{
int T;
int n;
int m;
cin>>T;
for(int i = 0;i<T;i++)
{
cin.ignore(); // 忽略掉上一次输入的回车
cin>>n;
List head;
InitList(head, n);
PrintList(head);
cin>>m;
InsertList(head, m);
PrintList(head);
DeleteList(head);
PrintList(head);
if(i<T-1)
cout<<endl;
}
}
```
通过添加 `cin.ignore()`,可以确保在循环开始时忽略掉之前输入的回车,使得输出结果不再多出一个回车。
阅读全文