2016-09-22 85 views
-2

這是我本網站上的第一個問題的話,我很抱歉,如果我做錯了什麼。在一個const char數組的索引比較爲char

我的問題是,我有一個應該在一個文本文件堆滿了信件閱讀,將每個字母的成字符數組,然後找到陣列中的每個字母量的計劃。

//i read in all the letters into the character array from my file and 
//display them to the screen to show that it works (and it does) 

//here is the for loop to go through the array 
// i am trying to check if the contents of the current index are C,S, or R. 
//by comparing them to characters. 

ifstream inputFile; 
     string path; 
     int cloud,rain,sun = 0; 
     char C = 'C'; 
     char R = 'R'; 
     char S = 'S'; 
     char array [3][30]; 
     cout << "The purpose of this program is to read in a text file and calculate a the number of days that were rainy." << endl; 
     do{ 
      cout << "Please enter the full path to the included \" Summer.txt\" file included witht this program." << endl; 
      cin >> path; 
      inputFile.open(path); 
      if(!inputFile){ 
       cout << "ERROR!!! No file was found at this location or there was a problem reading the file!" << endl; 

      } 
     }while(!inputFile); 
     if(inputFile){ 
      cout << "Success! The file was found and read!" << endl; 

      for(int r =0; r<3; r++){ //this is the loop to read in the text file 
      for (int c = 0; c < 30; c++){ 
       inputFile >> array[r][c]; 
      } 
     } 
     for(int r =0; r<3; r++){ //this outputs the array to the screen 
      for (int c = 0; c < 30; c++){ 
       cout << array[r][c] << " "; 
      } 
      cout << endl;  
     } 
     for(int r =0; r<3; r++){ //this is the loop to add up all the sun, cloud, and rain values. 
      for (int c = 0; c < 30; c++){ 
       if(array[r][c] == C){ 
        cloud++; 
       } 
       else if(array[r][c] == S){ 
        sun++; 
       } 
       else if(array[r][c] == R){ 
        rain++; 
       } 
      } 
     } 
      cout << "Sun = " << sun << " rain = " << rain << " cloud = " << cloud << "." << endl; 


     } 

    } 

唯一的問題是,當我輸出太陽雨和雲的值,我得到一個雲的隨機值。

是有辦法的字符數組的索引中的內容進行比較以信爲獲得一個布爾值?

+1

解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –

+1

rxu他有一個變量C ='C',所以這是有效的。雖然雲和雨是無意義的,這可能會解釋隨機未定義的行爲,但調試器可以提供幫助。 –

+0

寫每個字母的if語句太冗長乏味。更好地使用循環來做到這一點。像設置一個數組''char * letter ='abcdefg ... ABCDEFG'' 然後對於文檔中的每個字母,循環查看字母數組,以檢查字母數組中的每個字母是否與文檔中的字母匹配。 – rxu

回答

1

array[r][c] = Sarray[r][c] == S更換和array[r][c] = Rarray[r][c] == R.

更換同樣初始化雲,太陽和雨以0

0

你不應該需要一個2維數組,只使用單個字符陣列

char array [30] 

現在使用1個循環,而不是2和殼體/ switch語句,而不是IFS:

for (int i = 0; i < 30; i++) 
{ 
     switch (array[i]) 
     { 
     case 'C': 
     cloud++; 
     break; 
     case 'R': 
     rain++; 
     break; 
     case 'S': 
     sun++; 
     break; 
     } 
} 
0

好,看來,我的布爾比較是好的,但是當我宣佈
INT雲,雨,陽光= 0;顯然,我只是宣佈太陽等於0. 更改此爲每個聲明分配一個變量固定我的程序!