how to finish the input?

A

asdf

string text_word;
while (cin>>text_word)
vector1.push_back(text_word);

I just want to input two strings, how to terminate the input ? I press
Enter key, but it didn't terminate input.
 
T

Thomas Tutone

asdf said:
string text_word;
while (cin>>text_word)
vector1.push_back(text_word);

I just want to input two strings, how to terminate the input ? I press
Enter key, but it didn't terminate input.

The "while" construct is for loops. You don't need a loop in this
program. Why are you using "while"?

Best regards,

Tom
 
S

Stuart Redmann

asdf said:
string text_word;
while (cin>>text_word)
vector1.push_back(text_word);

I just want to input two strings, how to terminate the input ? I press
Enter key, but it didn't terminate input.

This depends on the platform you are using. Under Windows you have press
Ctrl + Z, under Unix Ctrl + D to issue an EOF.

Regards,
Stuart
 
D

Default User

asdf said:
string text_word;
while (cin>>text_word)
vector1.push_back(text_word);

I just want to input two strings, how to terminate the input ? I press
Enter key, but it didn't terminate input.


That because newline is just another white space to >>. My
recommendation is to use some sort of counting loop.


void GetStrings(std::vector<std::string> &v, int n)
{
std::string s;
char c;

std::cout << "> ";

for (int i = 0; i < n; i++)
{

std::cin >> s;
v.push_back(s);
}

std::cin.get(c); // eats the newline hanging out
}



Brian
 
D

Default User

Thomas said:
The "while" construct is for loops. You don't need a loop in this
program. Why are you using "while"?

Yes, he does. He wants to read two words out of one input line.



Brian
 
D

Default User

Stuart said:
This depends on the platform you are using. Under Windows you have
press Ctrl + Z, under Unix Ctrl + D to issue an EOF.


This sort of answers the OP's question, but a platform-independent
solution is probably better.




Brian
 
D

Default User

Thomas said:
The "while" construct is for loops. You don't need a loop in this
program. Why are you using "while"?


I had another reply to your message that I canceled, however it may
show up anyway. This is a more accurate reply.

A loop is one way of doing it, I presented one in another message.
Obviously another way is to have repeated code. That's not the most
efficient way in general, although for two it probably doesn't make
that much difference.




Brian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top