15,749,281 members
1.00/5 (1 vote)
See more:
Given a sample string "hello there are 200 apples and each apple weighs 100 to 300 grams". I have to count number of words which are integers like 200,100,300. How to do it. any code snippets in C, C++ will do .

What I have tried:

I cant figure a logic. I have no idea about how to extract integers from string
Posted
Updated 16-Nov-16 0:08am

Solution 2

Try, for instance:
C++
``` #include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;

int main()
{
string line = "hello there are 200 apples and each apple weighs 100 to 300 grams";

istringstream iss(line);

while ( iss.good() )
{
char *pe;
string s;
iss >> s;
long l = strtol(s.c_str(), &pe, 10);
if ( *pe == '\0')
cout << l << endl;
}

}```

C++
```
```

v2
Member 12852923 16-Nov-16 10:37am
Thank You it works. What is good() ?
CPallini 16-Nov-16 13:10pm
"What good's a computerized nose" :-)

See
http://www.cplusplus.com/reference/ios/ios/good/

Solution 1

That is really easy done in 2 step.

1. split the string in words (substring) with a string tokenizer. Already handled here.
2. test all substring if the are integers with atoi.

You need only the strtok and atoi functions and write some code. ;-)

Solution 3

Quote:
How to do it. any code snippets in C, C++ will do .

We do not do your HomeWork.
HomeWork is not set to test your skills at begging other people to do your work, it is set to make you think and help your teacher to check your understanding of the courses you have taken and also the problems you have at applying them.
So, give it a try, reread your lessons and start working. If you are stuck on a specific problem, show your code and explain this exact problem, we might help.

As programmer, your job is to create algorithms that solve specific problems and you can't rely on someone else to eternally do it for you, so there is a time where you will have to learn how to. And the sooner, the better.
When you just ask for the solution, it is like trying to learn to drive a car by having someone else training.

Quote:
I cant figure a logic. I have no idea about how to extract integers from string
You have to think to how you would do it with a sheet of paper and a pencil.

v2
Member 12852923 16-Nov-16 10:35am
Its not a home work. If you want to help please help but dont say stupid things
Patrice T 16-Nov-16 15:32pm
This is HomeWork.
This kind of problem is a problem only for very beginners and the only purpose of these problems is to make you think and try to devise an algorithm that solve that problem.
[no name] 16-Nov-16 21:46pm
Help isn't always someone doing your job for you. The only thing you learned here today is that if you ask someone to do your homework for you, someone will do it. Maybe you should try it yourself first before begging someone to do it for you. Than you might learn something.