Rahul
Rahul

Reputation: 47

how to stop while loop running for storing data in vector

i am using while loop for storing integer data in a vector like this :

vector<int> a;
int data=1;
cout<<"Enter data (Press Ctrl+Z to end)";

while(data)
        {
            cin>>data;
            if(data)
                a.push_back(data);
        }

this loop goes infinite the reason i found out after tacing is that when i enter Ctrl+Z (eof) to read in data it does not take that value and because last value is still there in data the loop runs again

Enter data (Press Ctrl+Z to end)23 //data=23
56 //data=56
45 //data=45
^Z // still data=45

i don't want to use condition with a specific number to end the loop like Enter -1 to end and user to specify the number of items to store in vector in advance. Is there any other way i can end the loop by using Ctrl+Z or any other string like done, finish etc..

Upvotes: 0

Views: 906

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490328

I'd skip the loop and read the data with a pair of istream_iterators:

cout<<"Enter data (Press Ctrl+Z to end)";

std::vector<int> a{std::istream_iterator<int>(std::cin),
                   std::istream_iterator<int>()};

Note that this will stop reading when it reaches the end of the input or it encounters something that can't be converted to an int (e.g., any character other than a digit or white-space).

If you really need to read all input (and convert numbers where you find them), you have a couple of choices. One I'd probably use would be to create a ctype facet that classifies everything except digits as white space, so the istream will just ignore everything except the numbers.

Another possibility (that some people might find more straightforward, even though it'll probably be more complex) is to read a line at a time with std::getline, then search in that string for a digit and convert that group of digits to an int. This gets particularly ugly if you might have more than one int on a line, so you need to re-start your search for digits after the end of the one you just converted.

Also note that control+Z only works on Windows, and isn't even particularly dependable there. You normally want to use F6 instead. For control+Z to work, you need to use enter control+Z enter.

Upvotes: 2

Threadicide
Threadicide

Reputation: 126

if(data) a.push_back(data);

This is flawed because if you input 0 the if will evaluate as false.

Upvotes: 0

Zeta
Zeta

Reputation: 105905

while(cin >> data){
    a.push_back(data);
}

Note that the EOF is usually set by using Ctrl+D, not Ctrl+Z (which will instead let your program sleep).

Upvotes: 2

Related Questions