我正在尝试从空格分隔的整数输入中创建一个链表。
输入:
- 节点数
- 空格分隔的输入
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/