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;
}
校验和是tcp里采用的校验和吗?还是求一个唯一对应的值。具体的使用场景是什么?
– ColdplayFan 5年前@ColdplayFan: 输入一个字符串,需要是4的倍数,不够的话补0,然后将他们的ASI||码值加起来输出
– 黄颖斌 5年前,系统会自动将字符转化成阿斯克码值,所以这一步不用管