什么原因导致字符计数不准确,真的很大? [英] What causes character counts from cin inaccurate and really large?
问题描述
我通过 char c = cin.get()
执行字符计数。我的输出示例为:
a:53
b:32
c:29 等。
I'm doing a character count via char c = cin.get()
. Example of my output would be:
a: 53
b: 32
c: 29 etc..
对于其中一个字母,我得到一个疯狂的大9位数字。然后,当我使用另一个具有更多字符的输入文件时,数字为6位数,太大以致不准确。这种表型的任何想法?
For one of the alphabets, I'm getting an insanely large 9-digit number. And then when I use another input file that has more characters, the numbers are 6-digits and too large to be accurate. Any thoughts of this phenotype?
再次,对不起,这是学期结束时的紧缩时间。
Again, sorry it's crunch time with the end of the semester. I appreciate any help out there.
int main (int argc, char *argv[])
{
int count [26] = { };
char alpha [26] = { };
char c;
c = cin.get();
while(!cin.eof())
{
if (isalpha(c))
{
c = tolower(c);
}
count [ c - 'a']++;
alpha [ c - 'a'] = c;
c = cin.get();
}
for ( int i = 0; i<26; i++ )
{
cout << alpha[i] << ":" << count[i] << endl;
}
} //end main
:(编辑)
a:224
b:50
c:70
d:20
e:167772180
f:10
g:40
h:66
i:28
这里是输入:(编辑)
aaaaaaaaAAAAAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaBBBB
aaaaaaaaAAAAAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAAAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaBBBB
进行这些更改,但仍然挂起:
Made these changes, but it's still "hanging":
c = cin.get();
while(c=cin.get())
{
c = tolower(c);
if (isalpha(c))
continue;
count [ c - 'a']++;
alpha [ c - 'a'] = c;
}
for ( int i = 0; i<26; i++ )
{
cout << alpha[i] << ":" << count[i] << endl;
}
} //end main
推荐答案
如果输入文件包含除字母以外的任何内容,任何情况都可能发生,因为您正在访问数组超出边界索引。也许你的意思是:
If the input file contains anyting else than letters, anything can happen because you are accessing the array wtih out of bounds indices. Maybe you meant:
while(!cin.eof())
{
if (isalpha(c))
{
c = tolower(c);
count [ c - 'a']++;
alpha [ c - 'a'] = c;
}
c = cin.get();
}
当您的数据包含换行符(10)时,您正在访问索引为10 - 97 = -87的 alpha
。这可能将10写入 count [4]
的最高有效字节。
E.g. when your data contains a line feed character (10) you are accessing alpha
with index 10 - 97 = -87. And this probably writes 10 into the most significant byte of count[4]
.
这篇关于什么原因导致字符计数不准确,真的很大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!