将const char数组中的索引与char进行比较

时间:2016-09-22 19:53:23

标签: c++ arrays comparison character

这是我在这个网站上的第一个问题,如果我做错了,我很抱歉。

我的问题是我有一个程序应该在一个充满字母的文本文档中读取,将每个字母放入一个字符数组,然后找到数组中每个字母的数量。

//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;


        }

    }

唯一的问题是当我输出太阳雨和云的值时,我会得到云的随机值。

有没有办法将字符数组的索引内容与字母进行比较以获得布尔值?

3 个答案:

答案 0 :(得分:1)

array[r][c] = S应替换为array[r][c] == S,而array[r][c] = R应替换为array[r][c] == R.

用0来初始化云,太阳和雨。

答案 1 :(得分:0)

你不应该需要一个二维数组,只需使用一个char数组

char array [30]

现在使用1循环而不是2和case / switch语句而不是ifs:

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

答案 2 :(得分:0)

好吧,看来我的布尔比较没问题,虽然我宣布了     int cloud,rain,sun = 0; 显然,我只是宣称太阳等于0。 改变这个来为每个声明分配一个变量来修复我的程序!