2015-05-08 90 views
-5
for (cout << "\nEnter the Sentence now:"; 
    cin >> Ascii; 

cout << "The ascii value of each letter you entered, added to the offset factor is: " 
    << (int)Ascii + RandomNumberSubtract << endl); 
+7

WT ...你爲什麼要這樣做? – ChiefTwoPencils

+0

我認爲你需要發佈更多的代碼,以便那些想要幫助你瞭解你在做什麼的人。 – arandomguy

+0

for循環執行下一條語句,並且這總是隻有1件事。但是你的'for循環'病態形成。你應該查看它,但我會提供的提示是「for(int i = 0; i <56; ++ i){/ *在這裏做一件事* /} –

回答

0

我強烈建議你把這個循環變成while循環。但是,無論您是否執行以下操作:

只需輸入EOF,循環將終止。

如何輸入EOF取決於您的操作系統(也可能取決於您的終端設置)。在Linux上(在默認終端設置下),您將得到一個EOF按Ctrl + D在行首。在Windows上,我認爲它是Ctrl + Z。在Mac上,我不知道。

當然,您也可以將程序的stdin重定向到來自文件(在這種情況下EOF是 - 如您猜測的那樣 - 在文件的末尾生成),或者從管道(在這種情況下生成EOF)只要寫作程序關閉管道)。

如果變量Ascii是char類型或字符串的沒有,你也可以輸入一些不能被解析爲變量的數據類型(例如,如果讀取int,比一些其他任何事情都會導致流報告故障,因此循環終止)。

您也可以在循環體(在您的for循環當前只是一個空語句)中添加另一個結束條件,然後。例如,你可能會決定百分號應該終止你的循環;然後你可以寫(我仍然假設你沒有提供的Ascii類型是char):

cout << "\nEnter the Sentence now:"; 
while(cin >> Ascii) 
{ 
    cout << "The ascii value of each letter you entered, added to the offset factor is: " 
     << (int)Ascii + RandomNumberSubtract << endl); 
    if (Ascii == '%') 
    break; 
} 

但是請注意,通常operator<<跳過空白;我想你不希望跳過空格。因此你可能不應該使用operator<<而是使用get;這也將允許您使用行的末尾爲結束條件:

cout << "\nEnter the Sentence now:"; 
while(std::cin.get(Ascii) && Ascii != '\n') 
{ 
    cout << "The ascii value of each letter you entered, added to the offset factor is: " 
     << (int)Ascii + RandomNumberSubtract << endl); 
} 

然而,在這種情況下,最好是閱讀行一步到位,然後遍歷它:

cout << "\nEnter the Sentence now:"; 
std::string line; 
std::getline(std::cin, line); 
for (std::string::iterator it = line.begin; it != line.end(); ++it) 
{ 
    cout << "The ascii value of each letter you entered, added to the offset factor is: " 
     << (int)*it + RandomNumberSubtract << endl; 
} 

注在C++ 11中,你可以簡化成

cout << "\nEnter the Sentence now:"; 
std::string line; 
std::getline(std::cin, line); 
for (auto ch: line) 
{ 
    cout << "The ascii value of each letter you entered, added to the offset factor is: " 
     << (int)ch + RandomNumberSubtract << endl; 
} 
2

也許最好的建議是不要聰明。你不僅難以讓其他人閱讀,理解和修改你的代碼,而且還會冒着自我超越的危險。

因此,不要試圖做怪異和聰明的事情來實現你的循環。自然而然地做事。如果他們不自然適合如何forwhiledo ... while語句的結構,然後只寫一個通用循環,並使用break語句來處理離開循環。例如

while (true) { 
    // Some stuff 
    if (i_should_break_out_of_the_loop) { 
     break; 
    } 
    // Some more stuff 
} 

這是不是做這樣的事情在你的方式折磨for聲明幾乎總是更好的。

一旦你有一個清晰,易於理解的循環,修改它以適應你的需求應該相對容易。 (或問一個更清晰,更專注的問題)

*:「其他人」也包括你三個星期後,你有時間後,離開你的短期記憶。