Input at most 4 words
I would like to cin at most 4 words but I couldn't figure out a suitable algorithm.
I have tried the below one but obviously it doesn't work.
And I don't know either string or char array I should use.
1 2 3 4 5 6 7 8
|
int i(0),no(0);
string input[4];
char in[100];
cout<<"Please input the query string: ";
while(cin>>in[i]){
if(no>4||in[i]=='.')break;
if(in[i]==' ') no++;
i++;}
|
Use
std::string
instead of
char[]
You are making the code a bit too complicated. I wrote an example for you here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::stringstream in("word1 w2 w3 w4 w5 w6.");
std::string words[4];
for(int i = 0; i < 4; i++) {
in >> words[i];
std::cout << "words[" << i << "]: " << words[i] << std::endl;
}
return 0;
}
|
Topic archived. No new replies allowed.