Reputation: 3
I'm pretty new to C++ and I need to write a program that can count number of digits, characters, space symbols and other symbols. I decided to start with counting the number of digits. This is my code so far:
int main() {
int n = 0;
int numb = 0;
ifstream read("Data.txt");
n = symbCounter(n, read);
numb = numbCounter(n, read, numb);
cout << numb; // this is for quick testing
return 0;
}
int symbCounter(int &n, ifstream &read) {
char ch;
while (!read.eof()) {
read.get(ch);
n++;
}
return n;
}
int numbCounter(int &n, ifstream &read, int counter) {
char sk[n];
for (int i = 0; i < n; i++) {
read.get(sk[i]);
if (sk[i] == '1' || sk[i] == '2' || sk[i] == '3' || sk[i] == '4' || sk[i] == '5' || sk[i] == '6' || sk[i] == '7' || sk[i] == '8' || sk[i] == '9' || sk[i] == '0')
counter++;
};
return counter;
}
But the console gives me the value 0. What am I doing wrong? And how do I count just characters, excluding digits or spaces? Thanks in advance.
Upvotes: 0
Views: 1127
Reputation: 1
You need to return the the beginning of the file for numCounter; right after
int numbCounter(int &n, ifstream &read, int counter) {
add
read.clear();
read.seekg(0, ios::beg);
Upvotes: 0
Reputation: 3912
You can use the functions defined in the <cctype>
header like
isalpha()
isblank()
iscntrl()
isdigit()
isspace()
and others to check for specific types of characters. See this for example.
Upvotes: 3
Reputation: 4996
In your symbCounter
method, you read through the file to the end. When you try to read from the file in your numbCounter
method, the calls to read
will return EOF
since you are at the end of the file. You can return to the beginning by calling
read.seekg(0);
Upvotes: 1