gpt4 book ai didi

c++ - 从空格分隔的输入创建链表

转载 作者:行者123 更新时间:2023-11-28 07:52:19 24 4
gpt4 key购买 nike

我正在尝试从空格分隔的整数输入中创建一个链表。

输入:

  1. 节点数
  2. 空格分隔的输入

int main()
{
int n;
cout<<"Enter number of nodes";
cin>>n;
cout<<"\nEnter data"<<endl;
int temp;
lNode *head = NULL;
while(cin>>temp)
{
CreateLinkedList(&head,temp);
}
PrintLinkedList(head);

return 0;
}

这里我不知道如何将用户输入限制为他作为第一个输入给出的节点数。有没有其他方式获取用户输入?

最佳答案

您可以要求输入为字符串:

string line;
getline(cin, line);

然后您可以使用 stringstream 分隔行中输入的数字,因此您应该包含 sstream 库(例如 #include <sstream> ):

stringstream ss(line);
int number;

while(ss >> number) {
... do whatever you want to do with the number here ...
}

关于c++ - 从空格分隔的输入创建链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13518510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com