C++:对一个空输入与空输入文件的反应
我对此还很陌生,所以这可能是非常简单的事情,我也可能在词汇方面失败,但无论如何我都会问,因为我自己无法弄清楚。
我正在制作一个程序,要求不同的命令来更改某些坐标,如果您给出一个空命令,它只会要求一个新命令。问题是,如果你给程序一个输入文件来读取命令 (像这样: ./我的程序<输入文件 ) 并且该文件是空的,它最终陷入循环并无休止地请求新命令。当没有更多输入可供读取时,它应该能够退出程序。但是,既然它无法知道命令是从文件中给出还是一次从一个文件中给出,那么它如何能发挥作用呢?或者有什么办法让它知道吗?毕竟,如果一次手动发出一个命令,一个空命令并不意味着不会有更多命令出现。我希望这听起来不太傻......
I'm still pretty new at this so this is probably something very simple and I might fail with vocabulary too, but I'll ask anyway because I just can't figure it out myself.
I'm making a program that asks for different commands to change certain coordinates and if you give an empty command it simply asks for a new command. The problem is that if you give the program an input file to read the commands from
(Like this:
./myprogram < inputfile
)
and that file is empty, it ends up in a loop and endlessly asks for a new command. It should be able to exit the program when there's no more input to be read. But how can it make a difference since it can't know if the commands are given from a file or one at a time? Or is there a way for it to know? After all, if they're given manually one at a time, one empty command doesn't mean there won't be more coming. I hope this doesn't sound too silly...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不完全确定“命令”适合您,但听起来好像您正在阅读单独的行并且想要排除空(或拼写错误)行。执行此操作的一个简单方法是读取行,但首先跳过前导空白,直到没有更多行:
表达式
in >> std::ws
跳过所有前导空白,即所有空格、换行符、制表符等。完成此操作后,std::getline()
读取一行内容并放入它进入行
。如果跳过前导空格后没有任何数据,则 std::getline() 会失败,因为已到达输入行。如果line
需要以某种方式解码,您可以将其放入std::istringstream
并从那里解码。I'm not entirely sure what a "command" is for you but it sounds as if you are reading individual lines and you want to exclude empty (or misspelled) lines. A simple way to do this is to read lines but first skip leading whitespace until there are no further lines:
The expression
in >> std::ws
skips all leading whitespace, i.e. all spaces, newlines, tabs, etc. Once this is done,std::getline()
reads the content of just one line and puts it intoline
. If there isn't any data after leading whitespace was skipped,std::getline()
fails because the line of the input was reached. Ifline
needs to be decoded in some way, you can just put it into astd::istringstream
and decode it from there.