从空格分隔的输入创建链接列表

时间:2012-11-22 18:45:34

标签: c++

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

输入:

  1. 节点数
  2. 空格分隔输入
  3. 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;
    }
    

    这里我没有得到如何将用户输入限制为他作为第一次输入给出的节点数。有没有其他方法可以获得用户输入?

1 个答案:

答案 0 :(得分:1)

您可以将输入作为字符串询问:

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 ...
}