0

I am trying to make a linked list from space separated integer input.

Input:

  1. Number of nodes
  2. Space separated input

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

Here I am not getting how to limit the user input to the number of nodes which he has given as first input. Is there any other way to get user input?

anatolyg
  • 26,506
  • 9
  • 60
  • 134
Ashwani K
  • 7,880
  • 19
  • 63
  • 102
  • 2
    `while(n-- && (cin>>temp))` seems like a possible idea. – WhozCraig Nov 22 '12 at 18:47
  • What's not working as you expect? – πάντα ῥεῖ Nov 22 '12 at 18:51
  • @WhozCraig Shouldn't this be `--n`?? – πάντα ῥεῖ Nov 22 '12 at 18:53
  • @g-makulik No. If n==1 going in the pre-decrement will drop it to zero and no data will be read. The post-decrement is intentional. side-effect note, btw. `n` will be (-1) when this loop breaks. – WhozCraig Nov 22 '12 at 18:53
  • @WhozCraig Yup, just noticed that as well ... – πάντα ῥεῖ Nov 22 '12 at 18:54
  • @WhozCraig: It is not reading any input after the count has exceeded, but the user is able to enter any number of integer until he presses enter. Can we limit the input to n? – Ashwani K Nov 22 '12 at 19:01
  • As-written the user must input at least `n` items. Anything beyond that will stay in the input stream. You can clear out unwanted data with `.ignore()`, but if you want actual interactive limits you're going to have to rethink how this is done. It sounds to me like what you're really fighting is std::cin buffering. Warning: **do not flush std::cin.**. It is undefined behavior. – WhozCraig Nov 22 '12 at 19:09
  • @WhozCraig: Actually I want to limit the user from entering data after he has entered n values. Any suggestions? – Ashwani K Nov 22 '12 at 19:13
  • [this](http://stackoverflow.com/q/4654636/942596) link should help. How to determine a string is a number. Also use a for-loop to limit the number of entries. – andre Nov 22 '12 at 19:15
  • You cannot stop the user typing, and you cannot stop what the user is typing from appearing in the console window. If you want to do that you are going to have to use much more advanced techniques than `cin`. Really I think you should stop worrying about trivial I/O issues and concentrate on the main point of your program which is *linked lists*. – john Nov 22 '12 at 19:55

1 Answers1

1

You can ask the input as a string:

string line;
getline(cin, line);

Then you can separate the entered numbers in the line using stringstream so you should include the sstream library (eg. #include <sstream>):

stringstream ss(line);
int number;

while(ss >> number) {
    ... do whatever you want to do with the number here ...
}
anatolyg
  • 26,506
  • 9
  • 60
  • 134
it2051229
  • 339
  • 3
  • 13