在一个const char数组的索引比较为char
问题描述:
这是我本网站上的第一个问题的话,我很抱歉,如果我做错了什么。在一个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;
}
}
唯一的问题是,当我输出太阳雨和云的值,我得到一个云的随机值。
是有办法的字符数组的索引中的内容进行比较以信为获得一个布尔值?
答
array[r][c] = S
应array[r][c] == S
更换和array[r][c] = R
应array[r][c] == R.
更换同样初始化云,太阳和雨以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;
}
}
答
好,看来,我的布尔比较是好的,但是当我宣布
INT云,雨,阳光= 0;显然,我只是宣布太阳等于0. 更改此为每个声明分配一个变量固定我的程序!
解决此类问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您应该\编辑您的问题,以包含一个[最小,完整和可验证](http://*.com/help/mcve)示例,该示例再现了您的问题,以及您在调试器。 –
rxu他有一个变量C ='C',所以这是有效的。虽然云和雨是无意义的,这可能会解释随机未定义的行为,但调试器可以提供帮助。 –
写每个字母的if语句太冗长乏味。更好地使用循环来做到这一点。像设置一个数组''char * letter ='abcdefg ... ABCDEFG'' 然后对于文档中的每个字母,循环查看字母数组,以检查字母数组中的每个字母是否与文档中的字母匹配。 – rxu