2015-12-14 84 views
0

在這段代碼中,如何停止這段代碼的輸入,在HUBBARD的早期版本中,它的寫入使用Ctrl + D或Ctrl + z,但它不起作用。請幫助如何停止輸入命令?

#include <iostream> 
#include <string.h> 

using namespace std; 

int main() 
{ 
    char line[80]; 
    while(*line) 
    { 
     cin>>line; 
     if(*line) cout<<" "<<line<<" "<<endl; 
    } 
    return 0; 
} 
+1

通過輸入'\ 0' –

+0

你試過'按Ctrl + C'? –

+0

\ 0不工作 是的,Ctrl + c正在工作。 謝謝 –

回答

1

檢查流的EOF是否已達到需要做一點不同。當達到EOF時

#include <iostream> 
#include <string.h> 

using namespace std; 

int main() 
{ 
    char line[80]; 
    while(cin>>line) 
    { 
     cout << " " << line << " " << endl; 
    } 
    return 0; 
} 

cin >> line將評估爲false或是否有任何其他錯誤。因此當時while循環將會中斷。

如果您確實需要閱讀一條線,如變量line所示,請勿使用cin >> line。改爲使用std::getlinecin >> line不會讀取空格字符。 std::getline將讀取空白字符。

#include <iostream> 
#include <string.h> 

using namespace std; 

int main() 
{ 
    std::string line; 
    while(getline(cin, line)) 
    { 
     cout << " " << line << " " << endl; 
    } 
    return 0; 
} 
0

您可以通過使用不等於比較運算符的任何值(如0,$)來停止while循環。

while(*line!='0') 

當你輸入0時它會終止。 或通過使用$

while(*line!='$') 

當您將輸入$它將終止。 的完整代碼

#include <iostream> 
using namespace std; 
int main() { 

char line[80]; 
while(*line!='$') 
{ 
    cin>>line; 
    if(*line) cout<<" "<<line<<" "<<endl; 
} 
return 0;  
}