I'm grabbing input from a standard input stream. Such as,
1 2 3 4 5
or
1
2
3
4
5
I'm using:
std::string in;
std::getline(std::cin, in);
But that just grabs upto the newline, correct? How can I get input whether they are separated by newline OR whitespace(s) using only iosteam, string, and cstdlib?
#include <iostream>
using namespace std;
string getWord(istream& in)
{
int c;
string word;
// TODO: remove whitespace from begining of stream ?
while( !in.eof() )
{
c = in.get();
if( c == ' ' || c == '\t' || c == '\n' ) break;
word += c;
}
return word;
}
int main()
{
string word;
do {
word = getWord(cin);
cout << "[" << word << "]";
} while( word != "#");
return 0;
}
int main()
{
int m;
while(cin>>m)
{
}
}
This would read from standard input if it space separated or line separated .
std::getline( stream, where to?, delimiter ie
std::string in;
std::getline(std::cin, in, ' '); //will split on space
or you can read in a line, then tokenize it based on whichever delimiter you wish.
Use 'q'
as the the optional argument to getline
.
#include <iostream>
#include <sstream>
int main() {
std::string numbers_str;
getline( std::cin, numbers_str, 'q' );
int number;
for ( std::istringstream numbers_iss( numbers_str );
numbers_iss >> number; ) {
std::cout << number << ' ';
}
}
the user pressing enter or spaces is the same.
int count = 5;
int list[count]; // array of known length
cout << "enter the sequence of " << count << " numbers space separated: ";
// user inputs values space separated in one line. Inputs more than the count are discarded.
for (int i=0; i<count; i++) {
cin >> list[i];
}
Source: Stackoverflow.com