while(gets())不适用于大输入

时间:2017-12-01 08:17:38

标签: c

我想要反转每个字符串的每个单词,这个程序适用于少量输入。但是当我尝试输入许多行程序时,它会发生运行时错误 例如:如果"我输入讨厌你。"输出将是"我tupni etah .uoy"

 #include<stdio.h>

    int main(){
    //    freopen("output.txt","w",stdout);
        char string[256];
        int i,j,word_start;
        while(gets(string)){
        for(word_start=0,i=0;1;i++){
            if(string[i]==' '|| string[i]=='\0'){
            for(j=i-1;j>=word_start;j--)
                putchar(string[j]);
            putchar(' ');
            word_start=i+1;
            if(string[i]=='\0')
                break;
            }
        }
        putchar('\n');
        }
        return 0;
    }

编译器C ++ 11ISO

示例输入:

Assure polite his really and others figure though. Day age advantages end sufficient eat expression travelling. Of on am father by agreed supply rather either. Own handsome delicate its property mistress her end appetite. Mean are sons too sold nor said. Son share three men power boy you. Now merits wonder effect garret own. 

Attention he extremity unwilling on otherwise. Conviction up partiality as delightful is discovered. Yet jennings resolved disposed exertion you off. Left did fond drew fat head poor. So if he into shot half many long. China fully him every fat was world grave. 
This is the problem!!!
My email is a@aa@aaa.com@
every dot is a . but not all dots are .s
is it a good test case ?
aa.bb.aa.
a.....aaaa..a..a.a..a
''.'sd.f'df'.df.'f.'
...adf....fds....sdf
.,,;;,',[,;,

sdfklj ,s,df, /////sdfdf
123456 aasdf
     568  sdf a1b2c3 :)
i am r2d2.
adfsaf 4-34549230 3
adffsflkdajflkdsajflafda afdsf 9024334242342342
,.z,.czxvkjwoijeoinlkf 2890ilakjnnc
dsakff;kdsafdafsaf adfaf

样本输出应为

erussA etilop sih yllaer dna srehto erugif .hguoht yaD ega segatnavda dne tneiciffus tae noisserpxe .gnillevart fO no ma rehtaf yb deerga ylppus rehtar .rehtie nwO emosdnah etaciled sti ytreporp ssertsim reh dne .etiteppa naeM era snos oot dlos ron .dias noS erahs eerht nem rewop yob .uoy woN stirem rednow tceffe terrag .nwo 

noitnettA eh ytimertxe gnilliwnu no .esiwrehto noitcivnoC pu ytilaitrap sa lufthgiled si .derevocsid teY sgninnej devloser desopsid noitrexe uoy .ffo tfeL did dnof werd taf daeh .roop oS fi eh otni tohs flah ynam .gnol anihC ylluf mih yreve taf saw dlrow .evarg 
sihT si eht !!!melborp
yM liame si @moc.aaa@aa@a
yreve tod si a . tub ton lla stod era s.
si ti a doog tset esac ?
.aa.bb.aa
a..a.a..a..aaaa.....a
'.f'.fd.'fd'f.ds'.''
fds....sdf....fda...
,;,[,',;;,,.

jlkfds ,fd,s, fdfds/////
654321 fdsaa
     865  fds 3c2b1a ):
i ma .2d2r
fasfda 03294543-4 3
adfalfjasdklfjadklfsffda fsdfa 2432432424334209
fklnioejiowjkvxzc.,z., cnnjkali0982
fasfadfasdk;ffkasd fafda

1 个答案:

答案 0 :(得分:3)

除了不推荐使用gets之外,您的示例输入的某些行超过了为输入缓冲区保留的256。例如,示例输入的第一行包含327个字符。因此,您将产生未定义的行为,例如一个段错误但可能不那么明显。我建议使用fgets,例如fgets(string, 256, stdin),如果fgets(string, sizeof(string), stdin)被定义为string,您也可以写char string[256]。但请注意,如果您将sizeof(string)定义为类型stringchar *将无法正常工作,例如撰写char *string = malloc(256)时。