2015-12-05 65 views
1

當我的代碼的這部分運行時,它一下子彈出到控制檯中,並沒有給我一個輸入cin.get的數據的機會。 我需要更改cin.get,以便在每個cout後停止並讓我輸入數據。數據需要能夠包含空格,字母和數字,如果有幫助,我只需要能夠有1個空格。 感謝您的幫助cin.get的問題

編輯:我改變了所有的cin.get到cin和所有的char qx [10]到字符串qx。如果有人知道如何防止輸入空格,那麼它也會解決我的問題。

int max = 10; 
     int randomnumber; 

     srand(time(0)); 
     randomnumber = (rand() % max) + 1; 
     cout << randomnumber; 

     if (randomnumber == 1) 
     { 
      char q1[10]; 
      char q2[10]; 
      char q3[10]; 
      char q4[10]; 
      char q5[10]; 
      char q6[10]; 
      char q7[10]; 
      char q8[10]; 
      char q9[10]; 
      char q10[10]; 

      system("CLS"); 
      cout << "Quiz Version : A" << endl; 
      cout << "sdsdfg:"; 
      cin.get(q1, 10); 
      cout << endl <<"sdfg:"; 
      cin.get(q2, 10); 
      cout << endl << "asdf:"; 
      cin.get(q3, 10); 
      cout << endl << "sdsdfg:"; 
      cin.get(q4, 10); 
      cout << endl << "sdfgsdfg:"; 
      cin.get(q5, 10); 
      cout << endl << "dfgdf:"; 
      cin.get(q6, 10); 
      cout << endl << "zxcvzxc:"; 
      cin.get(q7, 10); 
      cout << endl << "erteetrre:"; 
      cin.get(q8, 10); 
      cout << endl << "dsfgasdgf:"; 
      cin.get(q9, 10); 
      cout << endl << "xvcbyht:"; 
      cin.get(q10, 10); 
     } 
     else if (randomnumber == 2) 
     { 
      char q1[10]; 
      char q2[10]; 
      char q3[10]; 
      char q4[10]; 
      char q5[10]; 
      char q6[10]; 
      char q7[10]; 
      char q8[10]; 
      char q9[10]; 
      char q10[10]; 

      system("CLS"); 
      cout << "Quiz Version : B" << endl; 
      cout << "sdsdfg:"; 
      cin.get(q1, 10); 
      cout << endl << "sdfg:"; 
      cin.get(q2, 10); 
      cout << endl << "asdf:"; 
      cin.get(q3, 10); 
      cout << endl << "sdsdfg:"; 
      cin.get(q4, 10); 
      cout << endl << "sdfgsdfg:"; 
      cin.get(q5, 10); 
      cout << endl << "dfgdf:"; 
      cin.get(q6, 10); 
      cout << endl << "zxcvzxc:"; 
      cin.get(q7, 10); 
      cout << endl << "erteetrre:"; 
      cin.get(q8, 10); 
      cout << endl << "dsfgasdgf:"; 
      cin.get(q9, 10); 
      cout << endl << "xvcbyht:"; 
      cin.get(q10, 10); 
     } 

回答

0

假設你可以使用std::string(如標籤/編輯建議):

如果更換

char q1[10]; 
//... 
char q10[10]; 

隨着

string q1; 
//... 
string q10; 

然後你可以使用std::getline獲得用戶可靠輸入:

cout << "Quiz Version : A" << endl; 
cout << "sdsdfg:"; 
getline(cin, q1); //Gets user input from cin and places it in q1 
0

我想你應該修改下面的代碼提到:

#include <iostream> 
using namespace std; 

#define NUM_ELEMS 3 
#define BUF_LEN 10 

main() 
{ 
    char s[NUM_ELEMS][BUF_LEN]; 

    int i = 0; 
    while (i < NUM_ELEMS && !cin.fail()) { 
    cout << "Enter some text: "; 
    cin.getline(s[i], BUF_LEN); 
    cout << "You entered '"<< s[i] << "'" << endl; 
    i++; 
    } 
}