2013-03-19 162 views
1

在下面的代碼中,我可能會多次輸入,做一些計算(如最後一個字符)並在最後打印..然後再次輸入直到5次?連續輸入字符如使用循環多次的字符串

#include <iostream> 
using namespace std; 
int main() 
{ 
    char name; 
    int i=0; 
    while(i != 5){ 

     while(!(name != '<' || name != '>')){ 
      cin>>name; 
      //do some calculation with the inputs 
      //cout<<name; 
     } 
     i++; 
     cout<<name; 
     //print the result of calculation this loop 
    } 
} 

出於某種原因,我不能使用string,或array,或break,並不會比其他iostream庫。是否有可能使用循環?什麼是替代品?

編輯::在上面的代碼中,我想確定什麼是上次輸入。如果我輸入asdf>,那麼我得到>>>>>。我想要它打印>並返回到循環中,並要求我再拍一次。

+1

目前還不清楚你堅持什麼。 「一些計算」部分?循環5次? – 2013-03-19 16:48:00

+0

假設在上面我輸入'asfas <'我得到'<<<<<'並且程序終止。我不想讓程序終止..相反,我想回到while循環裏面,這讓我更想輸入。 – 2013-03-19 16:48:51

回答

2

while後終止name保持任一或<>不復位內while的下一遭遇,這立即終止作爲name仍然是要麼<>之前。在復位namewhile或輕微重組之前:

while (cin >> name && !(name != '<' || name != '>')) 
{ 
} 
+0

謝謝我正在愚蠢.. :((應該早點實現。 – 2013-03-19 17:01:47

1

看起來你想製作一個指向角色的指針。這將表現得像一個數組,但實際上並不是一個數組,除了輸入和輸出外,它只需要#include <iostream>

char* name; 

您也可以嘗試使用字符的載體,但是這是圍繞着漫長的道路,將打破「不過<iostream>規則:

#include <vector> 
#include <iostream> 

using namespace std; 

vector<char> CharVec; 
vector<char>::iterator it; 

int main() 
{ 
    char input; 
    int i=0; 
    while(i != 5){ 
     if(input != '<'){ //this should be if, not while 
      CharVec.push_back(input); 
     } 
     i++; 
    } 
    //move print to outside the character entering loop 
    it = CharVec.begin(); 
    while(it != CharVec.end()) 
    { 
     cout << *it; 
     it++; 
    } 

}

+1

- 他說沒有陣列 - 他什麼也沒說,除了 2013-03-19 16:51:40

+0

我不能使用array ...或任何數據結構。在教授數組之前,這是h/w。是否有可能使用循環? – 2013-03-19 16:51:58

+0

從技術上講,我剛剛製作了一個像數組一樣的指針。矢量素材被認爲違反了規則,但是您的老師/教授會認爲'char * c'與'char c [5]'相同嗎? – xcdemon05 2013-03-19 16:54:30

2

的解決方案是在此行之前重置名稱變量:

while (!(name != '<' || name != '>')) { 

您需要什麼是這樣的:

name = 0; 

此外,我建議初始化變量之前進入第一個while循環。您也可以使用'\0'而不是0。儘管在內部沒有任何區別。該代碼只對大多數沒有經驗的用戶更有意義。

+0

這是我需要的。 – 2013-03-19 16:57:00

+0

hmjd的重組解決方案雖然比較酷。 – 2013-03-19 16:59:56