Reading a sentence until ENTER key pressed using 2-D char array

Gokul picture Gokul · Mar 29, 2015 · Viewed 13.3k times · Source

I need to read a sentence word by word until "ENTER" key is pressed. I used a do..while loop to read words until ENTER key is pressed. Please suggest me some conditions for checking ENTER key press (or) others ways for reading similar input.

#include<iostream>
#include<string.h>
using namespace std;

int main(){

     char a[100][20]={'\0'};
     int i=0;

     do{
        cin>>a[i++];
     } while( \\ Enter key is not pressed );

     for(int j= 0 ; j < i ; j++)
        cout<< a[j] << " "; 
    return 0;
 }

Answer

πάντα ῥεῖ picture πάντα ῥεῖ · Mar 29, 2015

The statement

cin>>a[i++];

blocks at the prompt already, until the ENTER key is pressed. Thus the solution is to read a single line at once (using std::getline()), and parse the words from it in a separate step.

As your question is tagged , you can do the following:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

int main() {
    std::string sentence;
    std::cout << "Enter a sentence please: "; std::cout.flush();

    std::getline(std::cin,sentence);
    std::istringstream iss(sentence);

    std::vector<std::string> words;
    std::string word;
    while(iss >> word) {
        words.push_back(word);
    } 

    for(std::vector<std::string>::const_iterator it = words.begin();
        it != words.end();
        ++it) {
        std::cout << *it << ' ';
    }
    std::cout << std::endl; return 0;
}

See the fully working demo please.


As an improvement the current standard provides an even simpler syntax for the for() loop:

    for(auto word : words) {
        std::cout << word << ' ';
    }