平时我们写一个小的控制台程序,如果从控制台读取数据的话,输错了是不支持回退的。很多我们使用的软件都是支持的,
在github上找了一个C版本的readline,简单封装了一下,供自己平时写小程序使用。
github地址: https://github.com/troglobit/editline
封装后代码如下:
头文件
#ifndef HANDLE_MODE_CONSOLE_MODE_H_
#define HANDLE_MODE_CONSOLE_MODE_H_
#include <stdio.h>
#include "editline.h"
#include <vector>
#include <string>
class ReadLineWrapper {
public:
ReadLineWrapper() = default;
ReadLineWrapper(const ReadLineWrapper &) = delete;
void operator = (const ReadLineWrapper &) = delete;
~ReadLineWrapper();
public:
std::string readLine();
private:
std::vector<char*> pData = {};
};
#endif
源文件
#include "consoleMode.h"
ReadLineWrapper::~ReadLineWrapper()
{
for (auto ptr : pData) {
if (nullptr != ptr) {
std::free(ptr);
}
}
}
std::string ReadLineWrapper::readLine()
{
char* p = readline("");
if (nullptr == p) {
return std::string("");
}
pData.push_back(p);
return std::string(p);
}