首页新闻找找看学习计划

c++求校验和

0
悬赏园豆:50 [待解决问题]

输入一个字符串,求其校验和,用创建类的方法做

黄颖斌的主页 黄颖斌 | 初学一级 | 园豆:152
提问于:2019-09-26 15:34

校验和是tcp里采用的校验和吗?还是求一个唯一对应的值。具体的使用场景是什么?

ColdplayFan 1个月前

@ColdplayFan: 输入一个字符串,需要是4的倍数,不够的话补0,然后将他们的ASI||码值加起来输出
,系统会自动将字符转化成阿斯克码值,所以这一步不用管

黄颖斌 1个月前
< >
分享
所有回答(1)
0

checksumhandler.h

#ifndef CHECKSUMHANDLER_H
#define CHECKSUMHANDLER_H
#include <string>
using namespace std;

class CheckSumHandler
{
public:
    CheckSumHandler();
    virtual ~CheckSumHandler();
    void handle();
private:
    bool check(const string& line);
    int getCheckSum(const string& line);
};

#endif // CHECKSUMHANDLER_H

checksumhandler.cpp

#include "checksumhandler.h"
#include <iostream>
CheckSumHandler::CheckSumHandler()
{

}

CheckSumHandler::~CheckSumHandler()
{

}

void CheckSumHandler::handle()
{
    string line;
    do{
        getline(cin, line);
        if(check(line)) {
            cout << "input string: "<<line << endl;
            cout <<"check sum: "<< getCheckSum(line)<<endl;
//            break;
        } else{
            cout <<"input string contain un ascill char,please input again"<< endl;
        }
    }while(true);
}

bool CheckSumHandler::check(const string &line)
{
    auto iter = line.begin();
    while(iter != line.end()){
        char value = *iter;
        if(!isascii(value)){
            return false;
        }
        iter++;
    }
    return true;
}

int CheckSumHandler::getCheckSum(const string &line)
{
    //判断位数,不足增加0
    size_t count = line.length();
    size_t mod = count % 4;
    string addstr("");
    string copystr = line;
    switch (mod) {
        case 0:
            break;
        case 1:
            addstr = "000";
            break;
        case 2:
            addstr = "00";
            break;
        case 3:
            addstr = "0";
            break;
        default:
            break;
    }
    string combineStr =copystr.append(addstr);
    size_t result = 0;
    auto iter = combineStr.begin();
    while (iter != combineStr.end()) {
        result += *iter;
        ++iter;
    }
    return result;
}

main.cpp

#include <iostream>
#include "checksumhandler.h"
using namespace std;

int main()
{
    cout << "begin checksum program" << endl;
    CheckSumHandler checksumHander;
    checksumHander.handle();
    return 0;
}
ColdplayFan | 园豆:215 (菜鸟二级) | 2019-10-11 16:43
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册