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.
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 ?
#include <iostream> //cout, endl
#include <fstream> //ifstream
#include <cctype> //isdigit()
int getASCII(char ch) //This will give us the ASCII code of the char
{
returnstatic_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 ;).