为什么这个程序的结果是三个十进制数"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>"

本文关键字:enter gt 两个 十六进制数 lt 程序 结果是 为什么 十进制数 三个 输入      更新时间:2023-10-16
#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;
}

请注意,如果您的输入为空,则第二个版本也是正确的。首先检查您的输入,然后将其插入向量。