在 ' 之后终止输入' (空格)字符

发布于 2024-10-19 04:12:07 字数 773 浏览 1 评论 0原文

我刚刚开始学习 C++,在一些练习题中遇到了一个我不太明白的问题。我需要能够以以下形式从控制台读取一行:

N A B C... etc.

其中 N 是一个数字,并且根据 N 的不同,以下输入将具有不同的类型和不同的数量。

我的方法是读取 N,然后根据 N 的内容询问不同的输入。但我必须接受一行上的所有输入,并且我无法获得任何形式的输入以在单个空格字符后终止。那么,在收到一个数字和一个空格字符后,我是否可以继续执行下一条语句?或者有更好的方法来解决这个问题吗?感谢是提前的。

编辑:

好吧,我想我已经弄清楚了,但我不完全理解它,所以我必须研究 istringstream。这就是我所拥有的。

vector<string> words;

string token, text;
getline(cin, text);

istringstream iss(text);

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

    words.push_back(token);

}

这是一个好方法吗,还是我应该采取另一种方法?如果有人可以的话,你能为我解释一下这些台词吗?

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

我想当它到达一个空格时会返回 true,同时用所有先前的字符填充令牌?

这让我很困惑。

getline(cin, text);

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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

探春 2024-10-26 04:12:07

表达式 cin >>无论n是数字类型还是字符串类型,n都会停在第一个空格处。我相信 scanf 也会做同样的事情,只要 %d 或类似格式序列后面有一个空格。

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.

倾其所爱 2024-10-26 04:12:07

您应该立即读入整行(根据要求),然后根据 N,您的代码应该检查输入的其余部分以确保其格式正确或打印出错误。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文