为什么这个程序的结果是三个十进制数"597, 295, 295,"输入两个十六进制数"255 127<enter>"
Why the result of this program is three decimal numbers "597, 295, 295," for input of two hexadecimal numbers "255 127<enter>"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <sstream> using namespace std;
void printer(int i) {
cout << setw(4) << i << ", "; }
int main() {
string s;
getline(cin, s);
stringstream input(s); //LINE I
vector<int> v1;
int i;
do {
input >> hex >> i;
v1.push_back(i); //LINE II
} while (!input.fail());
for_each(v1.begin(), v1.end(), printer);
return 0; }
同样,该程序输出文件内容t, r, e, e,
t r e
。我相信原因与上述问题非常相似。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <fstream>
using namespace std;
void printer(char c) {
cout << setw(2) << c << ", ";
}
int main ()
{
ifstream inputfile("input.txt");
vector<char> v1;
char c;
do
{
inputfile>>c;//LINE I
v1.push_back(c);
}
while (inputfile.good());//LINE II
inputfile.close();
for_each(v1.begin(), v1.end(), printer);
return 0;
}
这些是来自评估的问题。我需要了解原因。当然,知道纠正也会提高我的技能。但我需要解释为什么它不能那样工作。
您首先尝试读取,然后将结果推送到向量,然后检查是否发生了错误。这个顺序是错误的。
while (true) {
input >> hex >> i;
if (input.fail())
break;
v1.push_back(i);
}
替换
do
{
inputfile>>c;//LINE I
v1.push_back(c);
}
while (inputfile.good());//LINE II
跟
input >> hex >> i;
while (!input.fail()) {
v1.push_back(i); //LINE II
input >> hex >> i;
}
请注意,如果您的输入为空,则第二个版本也是正确的。首先检查您的输入,然后将其插入向量。
相关文章:
- EASTL矢量<向量<int>>连续的
- Alt+Enter 在 Win32 应用中,管理大小调整和分辨率
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- 修复完成输入后重复"enter names of teacher"?
- 在 wxWidgets 中的 wxTextCtrl 上手动触发 ENTER 键按下事件C++?
- 我如何使它,无论用户用空白字符串按 Enter 多少次,它总是打印"开始"字符串?
- 如果我按enter键,我如何退出c++中的循环
- 大多数代码不仅显示欢迎消息和"enter pin"?
- 如何防止按 Enter 后命令行关闭
- 如何输入每个单词在字符串数组中的句子,直到用户按Enter键
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- ImGui 使用'enter'和数字键盘'enter'作为ImGuiKey_Enter
- C 字符串比较“祝您好运”&gt;“再见”
- 如何在 while 循环C++中检查 int 输入是否为空或用户按 Enter 键
- 如何在 c++ 集中插入元素,直到按下 Enter 键
- 按下Enter时如何输入错误消息,但没有给出任何答案
- 按Enter在Enter之后,ReadConsoleInput仅读取第一个符号
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 如何在C 中按ENTER/返回键时退出程序循环
- C :询问用户输入而无需按使用汇编按ENTER