Define numbers in a .txt file

Hi,
I read a .txt file by using <fstream> library. How can I define the number in the content of this file ?
example: I want to count how may numbers in a .txt file that includes numbers and chars.

 
Last edited on
Can you please clarify your question? What do you mean by "defining a number"? :)
oh, sorry, my English is not good :) . I mean when we read a .txt file, I want to know how many numbers in the content of this file, ex: "erodfjcnpdfk2fjdofj4j5" there are 3 numbers in this string. How can I count ?
or others symbols like *, #, etc. I just want to know how many letters, not numbers or symbols...I hope you can understand.:)
Last edited on
Thanks for clarifying your question :). This is how you'd do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream> //cout, endl
#include <fstream> //ifstream
#include <cctype> //isdigit()

int getASCII(char ch) //This will give us the ASCII code of the char
{
    return static_cast<int>(ch);
}

int main()
{
    std::ifstream inputFile("test.txt", std::ios::in);
    char ch; //Character we read from the file
    int noOfDigits = 0; //Will hold the number of 'numbers'

    while(!inputFile.eof()) //Loop till we reach the end of the file
    {
        ch = inputFile.get(); //Get a character
        int asciiCode = getASCII(ch); //Get the ASCII code of the character

        //If the character is a number
        if(std::isdigit(asciiCode))
        {
            noOfDigits++; //Increment noOfDigits by 1
        }
    }

    //Output the result
    std::cout << "There are " << noOfDigits << " numbers in your file!" << std::endl;

    inputFile.close(); //Close the file

    return 0;
}


There are perhaps better ways but this is the way I know of ;).
Last edited on
oh, thanks so much :)
Topic archived. No new replies allowed.