Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Statement after while loop isn't executed

Tags:

c++

loops

I'm having a problem with while loop. The statement after while loop isn't executed, and I've no idea why. I'm new to C++ and can't figure out this. I'm trying to take some words as input from the user and store them in a string vector, just for the sake of practice. Here's my code:

#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>

using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;

int _tmain(int argc, _TCHAR* argv[])
{
    vector<string> list;
    string word;

    while( cin >> word )
    {
        list.push_back(word);
        cout << "Added " << word << endl;
    }

    cout << endl;
    cout << "Done" << endl;

    system( "PAUSE" );
    return EXIT_SUCCESS;
}

When i run this console application, i can see that the statements within while loop are executed and the messages "Added " but the message "done" is not displayed. I've tried this with by specifying other statements after while loop as well ( like a for loop fetching & display values from the same string vector ) but no statement after this while loop is executed. Only the statements before and within the while loop are executed and I've no idea why.

like image 646
Humza Khan Avatar asked Mar 22 '26 05:03

Humza Khan


2 Answers

As long as you enter valid strings the loop will continue. And just entering an empty line will not work, as then the input operator will just block until it reads a non-whitespace character. You need to actually "terminate" the string by pressing CTRL-Z (the end-of-file keyboard shortcut).


If you want to detect empty lines and use that for termination condition, you need to use std::getline:

std::string line;
while (std::getline(std::cin, line) && !line.empty())
{
    ...
}
like image 56
Some programmer dude Avatar answered Mar 24 '26 19:03

Some programmer dude


Your while loop does not end because cin will always return soemthing != 0 which means that you're trapped in an endless loop. What you need is another condition inside the loop that performs a break:

string stop_string = "exit";

while( cin >> word )
{
    if ( stop_string.compare(word) )
        break;

    list.push_back(word);
    cout << "Added " << word << endl;        
}

or you could use std::getline to detect empty lines like Joachim Pilebord suggested.

like image 40
Stefan Falk Avatar answered Mar 24 '26 19:03

Stefan Falk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!