Reputation: 31
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;
}
Upvotes: 2
Views: 4598
Reputation: 56557
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';
}
Upvotes: 0
Reputation: 206607
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;
}
Upvotes: 1