c++ 用cin.get()获取数据的问题

函数如下,输入形式“1 2 3 1 2 3 1 3”,要求分辨输入的每个字符,如果是数字则在链表上新建一个节点,并将其作为节点的值。但是调用该函数,然后引用链表的值却老提示内存不可写,请问这函数哪里错了?
void init(page * head)
{
char c;
page * h=head;
cout<<"输入页面号的引用串的序列:";
while((c=cin.get())!='\n')
{
if(c>='0'&&c<='9')
{
h=new page;
h->i=int(c-48);
h=h->next;
}
}
h=null;
return;
}

机构体得定义:
typedef struct Page
{
int i;
struct Page * next;
}page;
最新回答
纯家小可爱

2025-06-27 11:44:54

cin.get()是用来读取多余回车符号的。

保留cin.get()的时候,程序执行流程如下:
你输入的google+回车,被getline(cin, titles[i])读掉,然后你输入的10被cin >> ratings[i]读掉,10后面的回车被cin.get()读掉。然后正常进入下一次循环。

去掉cin.get()之后,流程如下:
google+回车,被getline读取。10被cin >> ratings[i]读取。10后面的回车,被下次循环里的getline()读取,从这里开始就出错了。
ぐ紷紷猪﹏☆

2025-06-27 08:47:41

void init(page *& head)
{
char c;
page * h=head;
if (null == h) {
h = new page;
head = h;
}
cout<<"输入页面号的引用串的序列:";
while((c=cin.get())!='\n')
{
if(c>='0'&&c<='9')
{
h->next = new page;
h = h->next;
h->i = int(c-48);
}
}
h->next = null;
return;
}