c++ - 在命令行小于号到达 eof 后多次使用 c++ iostream cin
问题描述
我正在测试来自 C++ Primer 5th edition 的自定义代码,以在运行程序时使用 Windows 命令行中的小于号读取排序的单词列表,然后要求用户输入要在列表中搜索的单词;但问题是,如果我在命令提示符中使用“小于号”,则代码将忽略进一步的 cin 输入请求,但是通过手动输入单词列表并使用 ctrl+z (^Z) 以 EOF 终止 cin 输入然后将该输入输入并清除 cin 标志到 goodbit (std::cin.clear();) 代码识别以下 cin 输入请求。那么在使用小于 < 登录命令行自动创建单词列表时应该怎么做才能达到相同的结果呢?
这是示例代码:
所以编译它并像这样运行它:a.exe < word_list.txt
并且它没有使用“std::cin >>寻求;” 适当地。
我还注释掉了一些对 std::cin.rdstate() 的测试,以通过忽略和清除 cin 来表明接收 eof 前后的 cin 状态是相同的。
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> text;
std::string word;
//std::cout << std::cin.rdstate() << std::endl;
while (std::cin >> word)
text.push_back(word);
std::cout << "Enter a word to search:" << std::endl;
std::string sought;
//std::cout << std::cin.rdstate() << std::endl;
std::cin.ignore(1, std::cin.eof());
std::cin.clear();
//std::cout << std::cin.rdstate() << std::endl;
std::cin >> sought;
// text must be sorted
// beg and end will denote the range we're searching
auto beg = text.begin(), end = text.end();
auto mid = text.begin() + (end - beg)/2; // original midpoint
// while there are still elements to look at and we haven't yet found sought
while (mid != end && *mid != sought) {
if (sought < *mid) // is the element we want in the first half?
end = mid; // if so, adjust the range to ignore the second half
else // the element we want is in the second half
beg = mid + 1; // start looking with the element just after mid
mid = beg + (end - beg)/2; // new midpoint, we do not have operator+ for iterators
}
if (*mid == sought)
std::cout << "the result (" << sought << ") was found";
else
std::cout << sought << " was not found";
return 0;
}
解决方案
推荐阅读
- javascript - 检索频道标识符的问题 - Discord.JS
- reactjs - 如何使用 MUI-Data-Tables 呈现列内的项目数组?
- firefox-addon - 如何在扩展清单中匹配 Firefox 的 about 页面?
- python - 使用 Python 从 XML 文件中获取文件 url
- html - 如何在 Xaringan 演示文稿中调整图像大小?
- java - javafx Metro 主题 - 表格视图颜色文本
- matlab - 如何在 Matlab 中绘制“多维”图形。(即每个点代表一个混淆 2x2 矩阵)
- c++ - 尝试在结构中接收模板并在 std::vector 上使用它
- php - 我如何获得缺少数组的日子?
- sql - 使用不同的日期值更新 oracle 日期列