這是我本網站上的第一個問題的話,我很抱歉,如果我做錯了什麼。在一個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;
}
}
唯一的問題是,當我輸出太陽雨和雲的值,我得到一個雲的隨機值。
是有辦法的字符數組的索引中的內容進行比較以信爲獲得一個布爾值?
解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –
rxu他有一個變量C ='C',所以這是有效的。雖然雲和雨是無意義的,這可能會解釋隨機未定義的行爲,但調試器可以提供幫助。 –
寫每個字母的if語句太冗長乏味。更好地使用循環來做到這一點。像設置一個數組''char * letter ='abcdefg ... ABCDEFG'' 然後對於文檔中的每個字母,循環查看字母數組,以檢查字母數組中的每個字母是否與文檔中的字母匹配。 – rxu