Read a string longer than 4096 bytes from stdin in C ++

I am trying to read a string with a length of the order of 10 ^ 5. I get the wrong string if the string size exceeds 4096. I use the following code

string a;
cin>>a;

This did not work, I tried to read the character by character by running the code

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

I did the necessary escaping to use getchar, this also had a problem with 4096 bytes. Can anyone suggest a workaround or point out the correct way to read it.

+4
source share
3 answers

Using this test program based on what you posted:

#include <iostream>
#include <string>


int main()
{
    std::string a;

    std::cin >> a;

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

I can do:

./a.out < fact100000.txt

and get the result:

456574

, "" , 4095. , - "". , , copy'n'paste, . 4 , , - . ( , , , , 450 , , ).

+2

, /, ++. , , stdin? .

, , , , , ++.

+2

, - .

, -.

. , , - .

MAX_INPUT _POSIX_MAX_INPUT;

.

, , .


.

:

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

,

, .

, - :

#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;
}
0

Source: https://habr.com/ru/post/1535182/


All Articles