我正在学习编程,我的一项任务是创建一个程序,以计算任何输入文本中的大写字母,小写字母和数字的数量文件。出于某种原因,在我的程序中,它已经确认被计数的小写字母的数量是一个可笑的大数字。我不知道如何解决这个问题。大写和数字的计数似乎很好。另外我对C++没有太多的知识,所以请不要把任何先进的东西,提前抱歉。C++计算文件中的小写字符,大写字符和数字
#include <iostream> #include <fstream> #include <cstring> using namespace std; void countfile(char *a, int &x, int &y, int &z) { int len = strlen(a); for (int i =0; i < len; i++) { for (char b = 'A'; b <= 'Z'; b++) { if (a[i] == b) x++; } } for (int i = 0; i < len; i++) { for (char b = 'a'; b <= 'z'; b++) { if (a[i] == b) y++; } } for (int i =0; i < len; i++) { for (char b = '0'; b <= '9'; b++) { if (a[i] == b) z++; } } } int main() { string fileName; ifstream fin; cout << "Enter a text file: "; getline(cin, fileName); fin.open(fileName.c_str()); if (!fin.good()) throw "I/O error"; int uppercount, lowercount, digitcount; while (true) { string s; getline(fin, s); char *a = new char[s.size()+1]; a = (char*)s.c_str(); if (!fin.good()) break; countfile(a, uppercount, lowercount, digitcount); } cout << "The file contains: " << endl; cout << uppercount << " uppercase letters" << endl; cout << lowercount << " lowercase letters" << endl; cout << digitcount << " digits" << endl; return 0; }
除了你的问题,当然你可以为变量提供比'a',''x','y','z'更好的名字。 –
请使用'std :: string'而不是字符数组。你将会有更少的问题。例如,数组在传递给函数时会失去它们的属性。所以,除了数组之外,还必须将数组的容量和大小传递给函数。 –
另请参阅'std :: isupper','std :: islower','std :: isalpha'和'std :: isdigit'。如果您仔细查看库,您可以节省大量编码和调试时间。 –