C++:对一个空输入与空输入文件的反应

发布于 2025-01-05 04:49:26 字数 322 浏览 1 评论 0原文

我对此还很陌生,所以这可能是非常简单的事情,我也可能在词汇方面失败,但无论如何我都会问,因为我自己无法弄清楚。

我正在制作一个程序,要求不同的命令来更改某些坐标,如果您给出一个空命令,它只会要求一个新命令。问题是,如果你给程序一个输入文件来读取命令 (像这样: ./我的程序<输入文件 ) 并且该文件是空的,它最终陷入循环并无休止地请求新命令。当没有更多输入可供读取时,它应该能够退出程序。但是,既然它无法知道命令是从文件中给出还是一次从一个文件中给出,那么它如何能发挥作用呢?或者有什么办法让它知道吗?毕竟,如果一次手动发出一个命令,一个空命令并不意味着不会有更多命令出现。我希望这听起来不太傻......

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 技术交流群。

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

发布评论

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

评论(1

北斗星光 2025-01-12 04:49:26

我不完全确定“命令”适合您,但听起来好像您正在阅读单独的行并且想要排除空(或拼写错误)行。执行此操作的一个简单方法是读取行,但首先跳过前导空白,直到没有更多行:

for (std::string line; std::getline(in >> std::ws, line); ) {
    process(line)
}

表达式 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:

for (std::string line; std::getline(in >> std::ws, line); ) {
    process(line)
}

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 into line. If there isn't any data after leading whitespace was skipped, std::getline() fails because the line of the input was reached. If line needs to be decoded in some way, you can just put it into a std::istringstream and decode it from there.

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