2014-12-03 102 views
0

我是新來的函數,並試圖獲得返回值的掛起。更改返回值

我做了一個打印文本的函數,但我希望它根據實際函數中發生的情況返回一個值。

這是一個例子:

int function(char a) 
{ 
    int b = 0; 

    if(a == 'a') 
    { 
     b++; 
    } 

     cout << "Example"; 

    if(b == 1){ 
     return 1; 
    } 
    else 
    { 
     return 0; 
    } 
} 

然而,在這種情況下,返回值將被「卡住」設置爲0,並不會更改爲1。有沒有一種方法,使返回值的可靠在函數中發生了什麼?或者這不是它應該如何完成的?

編輯:這是我正在處理的代碼。基本上這是瑞典語中的「Hang子手」遊戲。我想是的「wordCheck」函數返回一個值,如果所有的信中處處都(和單詞完成),但現在它只是返回0,即使「NC」是4

#include <iostream> 
#include <string> 
using namespace std; 

int wordCheck(char word[4], int c) 
{ 
    int nC = 0, a; 
    if(c != 1) 
    { 
     for (int i = 0; i < 4; i++) 
     { 
      if (word[i] == NULL) 
      { 
       word[i] = '_'; 
      } 

      else if (word[i] != '_') 
      { 
       nC++; 
      } 
     } 

     cout << "Ordet: "<< word[0] << " " << word[1] << " " << word[2] << " " << word[3] << endl << endl; 
    } 
    if(nC == 4){ 
     return 1; 
    } 
    else 
    { 
     return 0; 
    } 
} 

int main() 
{ 
    setlocale(LC_ALL,""); 

    char guess = 'l', word[50] = "bajs", letter[4] = {NULL, NULL, NULL, NULL}, null[4] = {NULL, NULL, NULL, NULL}; 
    int i = 0, d = wordCheck(null, 1); 

    do 
    { 
     i++; 
     system("cls"); 
     cout << "**********HÄNGA GUBBE**********" << endl; 
     cout << "*******************************" << endl; 
     cout << "*********GISSA PÅ ORDET********" << endl; 
     cout << "-------------------------------" << endl << endl; 
     wordCheck(letter, 0); 
     cout << "Gissning " << i << " : "; 
     cout << d; 
     cin >> guess; 

     if (guess == word[0]) 
     { 
      letter[0] = 'B'; 
     } 
     else if (guess == word[1]) 
     { 
      letter[1] = 'a'; 
     } 
     else if(guess == word[2]) 
     { 
      letter[2] = 'j'; 
     } 
     else if (guess == word[3]) 
     { 
      letter[3] = 's'; 
     } 
    } while (wordCheck(null, 1) != 1); 


    system("pause"); 
    return 0; 
} 

(COUT < < d僅僅是用於調試的返回值,還考慮到裸露的代碼不被拋光,這是一項正在進行的工作)

+0

@dasblinkenlight我不好,我編輯了這篇文章。這是一個錯字。 – user2166357 2014-12-03 20:14:59

+0

你想做什麼? – user3344003 2014-12-03 20:21:23

+0

它如何「卡住」?你嘗試過'function('a')'嗎? – crashmstr 2014-12-03 20:22:43

回答

1

如果我沒看錯你有傳遞的值到C wordcheck爲1函數,因爲你的if條件沒有運行,這不是完全增加nC的值...這就是爲什麼你總是得到0的回報。

您已通過1至詮釋三

wordcheck(NULL,1) 

,然後檢查if(c!=1)然後nC++這實際上是沒有發生,你的NC保持爲0,因此在未來如果條件你else { return 0; }是給返回值

+0

哦,是的抱歉,這是我的不好,這就是我的意思:P – user2166357 2014-12-03 20:14:01

+0

這樣可以解決您的問題嗎? – 3Demon 2014-12-03 20:14:42

+0

不,如果我在主函數中打印返回值(例如),它會顯示「0」,而不是「1」。 – user2166357 2014-12-03 20:16:00

-1

在do while循環中,您應該發送字母變量而不是空變量,因爲那是您要驗證的數組。

+0

是的,但這似乎並沒有幫助我的問題。 – user2166357 2014-12-03 20:48:53