天天看點

C++控制台輸入支援倒退

平時我們寫一個小的控制台程式,如果從控制台讀取資料的話,輸錯了是不支援回退的。很多我們使用的軟體都是支援的,

在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);
}