修羅 wrote:
> 一個簡單的程式
> 如果只用iostream.h和c++的指令
> 以及只用stdio.h和c的指令
> 那執行出來的結果都是正確的
>
> 但如果照著書裡的寫法同時使用iostream.h和stdio.h
> 雖然編譯正確..但執行結果卻是錯誤的 為何會如此?
>
> 例如
> #include<iostream.h>
> #include<stdio.h>
> const int length=80;
>
> void main(){
> char string[length];
> cout<<"\nEnter a string:";
> gets(string); /* c的指令gets() */
> cout<<"You entered:"<<string;
> }
>
> gets(string) 比兩個cout 還要早執行,使得結果變成
>
> A practical guide to C++
>
> Enter a string:You entered:A practical guide to C++
>
>
>
> 如果改成只有C或C++的語法,結果是正確的
>
> #include<stdio.h> /* c */
> const int length=80;
>
> void main(){
> char string[length];
> printf("\nEnter a string:");
> gets(string);
> printf("You entered:%s",string);
> }
>
>
> #include<iostream.h> //C++
> const int length=80;
>
> void main(){
> char string[length];
> cout<<"\nEnter a string:";
> cin.get(string,length);
> cout<<"You entered:"<<string;
> }
>
>
> 執行結果
> Enter a string:A practical guide to C++
> You entered:A practical guide to C++
在 Unix 下就算你全用 C 或 C++ 也是可能出問題
因為要有 \n 才會清 buffer
所以, 要是你printf 一串字串不是以\n結尾
要加 fflush(stdout);
要是是cout
就要 cout.flush();
--
PaulLiu(劉穎駿)
E-mail address:PaulLiu.bbs@bbs.cis.nctu.edu.tw