在不使用getline的情况下读取C 中的stdin

Reading stdin in c ++ without using getline

本文关键字:读取 中的 stdin 情况下 getline      更新时间:2023-10-16

我正在尝试转换程序(这是VSCODE和DEBUG之间的桥梁(该程序用C#。

编写

它基于o vscode-mono-debug

(https://github.com/microsoft/vscode-mono-debug/blob/master/src/src/protocol.cs(

好吧,在C#中,我可以将标准输入读为流:

 byte[] buffer = new byte[BUFFER_SIZE];
Stream inputStream = Console.OpenStandardInput();
    _rawData = new ByteBuffer();
        while (!_stopRequested) {
            var read = await inputStream.ReadAsync(buffer, 0, buffer.Length);
            if (read == 0) {
                // end of stream
                break;
            }
            if (read > 0) {
                _rawData.Append(buffer, read);
                ProcessData();
            }
        }

我尝试这个:

#define _WIN32_WINNT 0x05017
#define BUFFER_SIZE 4096
#include<iostream>
#include<thread>
#include <sstream>
using namespace std;
class ProtocolServer
{
    private:
        bool _stopRequested;
        ostringstream _rawData;
    public:
        void Start()
        {
            char buffer[BUFFER_SIZE];
            while (!cin.eof())
            {
                cin.getline(buffer,BUFFER_SIZE);
                if (cin.fail())
                {
                    //error
                    break;
                }
                else
                {
                    _rawData << buffer;
                }
            }
        }
};
int main()
{
    ProtocolServer *server = new ProtocolServer();
    server->Start();
    return 0;
}

输入:

Content-Length: 261rnrn{"command":"initialize","arguments":{"clientID":"vscode","adapterID":"advpl","pathFormat":"path","linesStartAt1":true,"columnsStartAt1":true,"supportsVariableType":true,"supportsVariablePaging":true,"supportsRunInTerminalRequest":true},"type":"request","seq":1}

这正确读取前2行。由于该协议并未在末尾放置 n,因此它陷入了3个交互中的cin.getline。

切换到read((导致它停留在cin.read((,根本没有读取任何内容。

我发现了一些类似的问题:stackoverflow问题

和示例:posix_chat_client

,但我不需要它一定是异步的,但它在Windows和Linux上起作用。

我很抱歉我的英语

谢谢!

您想要的是未形式的输入操作

这是使用STD :: iostream的1:1翻译。唯一的"技巧"是使用和尊重gcount()

std::vector<char> buffer(BUFFER_SIZE);
auto& inputStream = std::cin;
_rawData = std::string {}; // or _rawData.clear(), e.g.
while (!_stopRequested) {
    inputStream.read(buffer.data(), buffer.size());
    auto read = inputStream.gcount();
    if (read == 0) {
        // end of stream
        break;
    }
    if (read > 0) {
        _rawData.append(buffer.begin(), buffer.begin() + read);
        ProcessData();
    }
}

我个人建议丢弃read == 0检查更准确的检查:

if (inputStream.eof()) { break; }   // end of stream
if (!inputStream.good()) { break; } // failure

请注意,!good()也捕获eof(),因此您可以

if (!inputStream.good()) { break; } // failure or end of stream

实时演示

活在coliru

#include <iostream>
#include <vector>
#include <atomic>
struct Foo {
    void bar() {
        std::vector<char> buffer(BUFFER_SIZE);
        auto& inputStream = std::cin;
        _rawData = std::string {};
        while (!_stopRequested) {
            inputStream.read(buffer.data(), buffer.size());
            auto read = inputStream.gcount();
            if (read > 0) {
                _rawData.append(buffer.begin(), buffer.begin() + read);
                ProcessData();
            }
            if (!inputStream.good()) { break; } // failure or end of stream
        }
    }
  protected:
    void ProcessData() {
        //std::cout << "got " << _rawData.size() << " bytes: n-----n" << _rawData << "n-----n";
        std::cout << "got " << _rawData.size() << " bytesn";
        _rawData.clear();
    }
    static constexpr size_t BUFFER_SIZE = 128;
    std::atomic_bool _stopRequested { false };
    std::string _rawData;
};
int main() {
    Foo foo;
    foo.bar();
}

打印(例如,在阅读自己的源文件时(:

got 128 bytes
got 128 bytes
got 128 bytes
got 128 bytes
got 128 bytes
got 128 bytes
got 128 bytes
got 92 bytes