[C / C ++] record gets, cin.getline clear the word wrap

Competition often:

Input Format

  Line 1: 1 n, the number of instructions
  a first 2..n + 1 rows: an instruction is given for each row. Xxxxxxxx instruction sequence

Ah yes, then it is usually a lot of straight line and the following code:

int length=0;

char* inputText=(char*)malloc(xLength);

cin>>length;

for(int i=0;i<length;i++){

cin.getline(inputText,length);

...

Or pure C operation, 

int length=0;

char* inputText=(char*)malloc(xLength);

scanf(%d,&length);

for(int i=0;i<length;i++){

gets(inputText);

...

Thus, there will be less of the case to one line, because the front of the input when the user input stream there is also a carriage return, or gets below a first getline this symbol will be null data read for his party, resulting in a situation less of a line.

solution:

Pure C:

scanf (after) using getchar () absorbing a newline

int length=0;

char* inputText=(char*)malloc(xLength);

scanf(%d,&length);

getchar (); // absorbent wrap Gong

for(int i=0;i<length;i++){

gets(inputText);

...

 In C ++ STL library use cin.ignore () ignores previous data stream, ignored here, that is in front of that line breaks

int length=0;

char* inputText=(char*)malloc(xLength);

cin>>length;

cin.ignore (); // this is absorbed. (Cin.ignore () other parameters, refer to the specific usage Baidu or MSDN, competition here is a method may be used. Do not as a standard)

for(int i=0;i<length;i++){

cin.getline(inputText,length);

...

After the above process generally can achieve our competition topic asks friends. 

Published 18 original articles · won praise 8 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_20408397/article/details/83685568