0

I just starting out in C++ and I've reached a problem in some practice questions that I can't quite figure out. I need to be able to read a line from the console in the form of:

N A B C... etc. 

Where N is a number, and the following input will be of different types and different amounts based on what N is.

My approach would be to read N and then ask for the different inputs based on what N is. But I have to accept all the input on a single line, and I haven't been able to get any form of input to terminate after a single space character. So is there anyway I could move on to the next statement after receiving a single number, and a space character? Or is there a better way to go about this problem? Thanks is advance.

EDIT:

Okay I think I've figured it out but I don't completely understand it, so I'll have to look into istringstream. Here's what I have.

vector<string> words; string token, text; getline(cin, text); istringstream iss(text); while ( getline(iss, token, ' ') ) { words.push_back(token); } 

Is this a good way to do it, or should I be taking another approach? And if anyone could, can you explain these lines for me?

while ( getline(iss, token, ' ') ) 

I guess this returns true when it reaches a space, while filling up token with all previous characters?

And this one confuses me.

getline(cin, text); 

2 Answers 2

3

The expression cin >> n will stop on the first space, whether n is a number type or a string type. I believe scanf will do the same, as long as there is a space after the %d or similar format sequence.

Sign up to request clarification or add additional context in comments.

2 Comments

Maybe I forgot to test this, but will this move to the next line of code without hitting return? I can't test this myself at the moment.
@Kzone272 – It will block until you hit return, but it will only take the first token for n. The rest of the line will be buffered for later input.
1

You should read in the entire line at once (as requested) and then depending on N, your code should check the rest of the input to make sure it is properly formatted or print out an error.

3 Comments

But how would I read in a line of a varying number of inputs without using getline() and a string type or something?
You could read in the entire line (without knowledge of how many inputs they entered) and then tokenize on the space character, reading in the first token (or N). After figuring out what N is, then you can read in the rest of the expected tokens. How you check erroneous input is up to you.
Okay I think I've got it. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.