如何从C++中的标准输入读取n个整数?
我需要阅读类似的内容:
5 60 35 42
2 38 6
5 8
300 1500 900
然后将第一行保存在数组中。调用其他函数后,对下一行执行相同的操作,依此类推。
我尝试使用 gets() ,然后使用 sscanf() 扫描字符串中的整数,但我不知道如何从字符串中读取 n 个数字。
I need to read something like:
5 60 35 42
2 38 6
5 8
300 1500 900
And then save the first line in an array. After calling other functions do the same with the next line, and so on.
I try with gets()
and then use sscanf()
to scan the integers from the string, but I don't know how to read n numbers from a string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
C++
如果您有未知数量的条目分布在未知数量的行上,并以 EOF 结尾:
如果您有已知数量的条目分布在未知数量的行上:
如果您在单行上有未知数量的条目:
如果未知数量的条目分布在已知数量的行中:
C++
If you have an unknown number of entries spread across an unknown number of lines, ending at EOF:
If you have a known number of entries spread across an unknown number of lines:
If you have an uknown number of entries on a single line:
If you have a unknown number of entries spread across a known number of lines:
我以前见过这样的比赛输入文件。如果速度比错误检测更重要,您可以使用自定义例程。这是与我使用的类似的:
如果一行上的字符超过 100 个,或者数字超过数组可以容纳的数量,它将破坏您的内存,但您不会获得更快的例程来读取无符号整数行。
另一方面,如果你想要简单:
I've seen input files like this for competitions before. If speed is more of an issue than error detection, you could use a custom routine. Here's one similar to that I use:
It will destroy your memory if there's more than 100 characters on a line, or more numbers than array can hold, but you won't get a faster routine to read in lines of unsigned ints.
On the other hand, if you want simple:
我可能会写这样的代码:
I'd probably write the code something like this:
在 C++ 中,您可以使用
std::istringstream
。如果您想从标准输入获取它,请执行相同的操作,但只需使用
std::cin
In C++, you can use
std::istringstream
.If you want to get it from the standard input, then do the same, but just use
std::cin
快速的解决方案是使用
scanf()
< 阅读它们/a>这仍然需要更多验证......
The quick solution is to read them with
scanf()
This still needs a bit more validation ...
C++:
替代方案(感谢 Shahbaz)
C++:
Alternative (thx to Shahbaz)
在 C++ 中,通过 stdin 读取由空格分隔的 N 个整数非常简单:
In C++ it's extremely simple to read N integers separated by whitespace via stdin: