gpt4 book ai didi

c++ - C++中从stdin中读取长度大于4096字节的字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:53:34 24 4
gpt4 key购买 nike

我正在尝试以 10^5 的顺序读取一个长度的字符串。如果字符串的大小超过 4096,我会得到不正确的字符串。我正在使用以下代码

string a;
cin>>a;

这没有用,然后我尝试通过以下代码逐字符读取

unsigned char c;
vector<unsigned char> a;
while(count>0){
c = getchar();
a.push_back(c);
count--;
}

我已经为使用 getchar 做了必要的转义,这也有 4096 字节的问题。有人可以建议解决方法或指出正确的阅读方式。

最佳答案

这是因为您的终端输入在 I/O queue 中进行了缓冲内核。

Input and output queues of a terminal device implement a form of buffering within the kernel independent of the buffering implemented by I/O streams.

The terminal input queue is also sometimes referred to as its typeahead buffer. It holds the characters that have been received from the terminal but not yet read by any process.

The size of the input queue is described by the MAX_INPUT and _POSIX_MAX_INPUT parameters;

默认情况下,您的终端位于 Canonical mode .

In canonical mode, all input stays in the queue until a newline character is received, so the terminal input queue can fill up when you type a very long line.


我们可以从canonical mode改变终端的输入模式至 non-canonical mode.

您可以从终端执行此操作:

$ stty -icanon (change the input mode to non-canonical)
$ ./a.out (run your program)
$ stty icanon (change it back to canonical)

或者您也可以通过编程方式进行,

要以编程方式更改输入模式,我们必须使用 low level terminal interface .

所以你可以这样做:

#include <iostream>
#include <string>
#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int clear_icanon(void)
{
struct termios settings;
int result;
result = tcgetattr (STDIN_FILENO, &settings);
if (result < 0)
{
perror ("error in tcgetattr");
return 0;
}

settings.c_lflag &= ~ICANON;

result = tcsetattr (STDIN_FILENO, TCSANOW, &settings);
if (result < 0)
{
perror ("error in tcsetattr");
return 0;
}
return 1;
}


int main()
{
clear_icanon(); // Changes terminal from canonical mode to non canonical mode.

std::string a;

std::cin >> a;

std::cout << a.length() << std::endl;
}

关于c++ - C++中从stdin中读取长度大于4096字节的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22886167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com