开发者

Terminating input after a ' ' (space) character

开发者 https://www.devze.com 2023-02-13 11:46 出处:网络
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:

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 开发者_如何学Cup token with all previous characters?

And this one confuses me.

getline(cin, text);


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号