C++单链表引出的cin问题

用C++实现一个单链表,在第123行输入想删除的结点时出现问题,cin语句直接被跳过。经检查发现,上一次使用cin时(creat函数中),最后一个输入字符为结束符。下次再使用cin时因为遇到结束符,直接无视输入,所以直接跳过了。解决方法:在下一次需要cin时先调用cin.clear进行输入重置(第121行)。


#include<iostream>
#include<string>
using namespace std;


struct node
{
	string s;
	node* next;
};


node* creat()
{
	string st;
	node *head, *now;
	head = new node;
	now = head;
	
	while(cin >> st)
	{
		now->s = st;
		now->next = new node;
		now = now->next;
	}
	now->next = NULL;


	return head;
}


int getlen(node* n)
{
	int length=0;
	if(n == NULL)
		return 0;
	else
	{
		while(n->next)
		{
			length++;
			n = n->next;
		}
		return length;
	}
}


void printlist(node* n)
{
	if(n == NULL)
		cout << "list is empty !" << endl;
	else
	{
		while(n->next)
		{
			cout << n->s << " ";
			n = n->next;
		}
		cout << n->s << endl;
	}
}


node* deletenode(node *head, string st)
{
	node *now,*temp;
	now = head;


	if(head->s == st)
	{
		head = head->next;
		delete now;
		now = NULL;
		return head;
	}


	while(now->s != st && now->next != NULL)
	{
		temp = now;
		now = now->next;
	}


	if(now->s == st)
	{
		temp->next = now->next;
		delete now;
		now = NULL;
		return head;
	}
	else
	{
		cout << "can not find " << st << endl;
		return head;
	}
}


node* insertnode(node* head, int pos)
{
	return head;
}


void main()
{
	string deletes;


	cout << "please input data: " << endl;
	node *head = creat();
	cout << "length of list: " << getlen(head) << endl;
	printlist(head);


	cout << "delete: " << endl;
	cin.clear();	//重置错误输入
    //cin.sync();		//清空缓冲区
	cin >> deletes;
	
	deletenode(head, deletes);
	printlist(head);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值