Hello, my name is Brian. I like to tra00123456789vel my phone number is 65254875245652 ok, tha156845ts not my tr5632e number
And I need to find only those words which contains only numbers f.ex 65254875245652, but tra00123456789vel is not correct becouse word contain numbers and words...
Here is my code
1 2 3 4 5 6 7 8 9
bool FindOnlyNumbersInMyTXTFile(string E){ // E - line
string sk = "0123456789";
for(int i=0; i<E.length(); i++){
if(sk.find(E[i])){
returntrue;
}
}
returnfalse;
}
1. You are searching the entire line at once
2. once you find even a single number on the line you return true.
Try and break the line into words, use the std::isdigit to see if every character in the word is a digit. Here's a quick old-timey example, you should use more modern C++ features in your own implementation.
#include <iostream>
#include <string>
#include <sstream>
usingnamespace std;
// really old way, also doesn't deal with decimal points, signs
// or number formats other than straightforward integral values
bool is_number(const string &word)
{
for (size_t i = 0; i < word.size(); ++i)
{
if (!isdigit(word[i]))
{
returnfalse;
}
}
returntrue;
}
int main()
{
string line("Hello, my name is Brian. I like to tra00123456789vel my phone number is 65254875245652 ok, tha156845ts not my tr5632e number");
istringstream iss(line);
string word;
while (iss >> word)
{
if (is_number(word))
{
cout << word << endl;
}
}
return 0;
}
It depends on what appeals to you the most. I must point out that the functions you're writing are neither as short nor as simple as the example I used.
Your last one won't work of course. It just doesn't do any of the things you're tying to.
Why don't you want to use isdigit()? The function is_number() does exactly what you want, in 3 statements, it is already very simple and very short. I suppose it could be shortened to 2 lines, but that reduces clarity and improves nothing.
Also show your full code, including main() and the #includes. Be very clear about what the problem is. It's just occurred to me that you've not actually stated what the problem is, and I'm beginning to wonder what's going on in the surrounding code.
Hi,
I'll just put up another example, based on my interpretation of what you're trying to do.
I've modified the code you gave above. I assume you have a file called "Tekstas.txt" in the current folder when running. "RedTekstas.txt" Will be created if it doesn't already exist.
I've mady very lazy changes (only 24 hours in a day :-)), but please pay attention to the changes, and carefully compare with the former code.
You should see the proper output on cout and also in RedTekstas.txt.