简体   繁体   中英

C++ - Read in input one word at a time

I'm trying to read in user input one word at a time until the user prints enter. Currently this works at reading until enter is pressed, but reads just one char at a time. Any suggestions on how to read by word instead?

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

int main(){

    char a[256];
    int i=0;

    do{
        cin>>a[i++];
     } while(cin.peek() != '\n');

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

You can try using

std::string a[256];

instead of

char a[256];

However, the the logic of using

while(cin.peek() != '\n');

is flawed. If you enter a space character before hitting Enter , your program will wait for you to enter more input.

It will be better to use std::getline() to read a line of text and then parse the line of text using a stringstream .

I am also going to suggest use of a std::vector<std::string> instead of an array of std::string .

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

int main()
{
   std::vector<std::string> words;

   std::string line;
   getline(std::cin, line);

   std::istringstream str(line);
   std::string word;
   while ( str >> word )
   {
      words.push_back(word);
   }

   for ( auto& w : words )
   {
      std::cout << w << " "; 
   }

   return 0;
}

Here is another compact way of doing it using getline and a container of std::string s

#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>

int main() 
{
    std::vector<std::string> tokens;
    std::copy(std::istream_iterator<std::string> {std::cin}, {}, 
              std::back_inserter(tokens));
    for(auto && elem: tokens)
        std::cout << elem << '\n';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM