how to take a number out of a string and turn it into an int.

I'm trying to make a program where the user enters a sentence consisting of words and numbers (I am 21 years old). and I need to break the sentence into words and print each word on its own line, if the word is a number then I need to double the number. So far I broke the sentences into words and got it to print on its own line. I don't know how to make the program detect a number and turn it into a double then reprint it.

For example: "I am 21 years old"

it should output:
I
am
42
years
old



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
  #include<iostream>
#include<string>
#include<cctype>
#include<algorithm>
#include<sstream>

using namespace std;

int main()
{
	string sentence;
	cout << "Enter a sentence: ";
	while ( getline(cin,sentence)) 
	{
		istringstream stream(sentence);
		string token;
		while(getline(stream, token, ' '))
		{
			
			cout << token << endl;
		}
	}

	

	system("PAUSE");
	return 0;

}
Last one before I hit the sack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
using namespace std;

int main() 
{
	string word;
	int num;
	
	while (!cin.eof())
	{
		while (cin >> num)
			cout << (num << 1) << endl;
		cin.clear();
		if (cin >> word)
			cout << word << endl;
	}
	return 0;
}
This thread explains some methods that you can use.
http://www.cplusplus.com/forum/unices/121866/
Last edited on
An alternative:

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
#include<iostream>
#include<string>
#include<sstream>

using namespace std;

int main()
{
    string sentence;
    cout << "Enter a sentence: ";
    while (getline(cin, sentence))
    {
        istringstream stream(sentence);
        string token;
        while (stream >> token)
        {
            try {
                double value = std::stod(token);
                value *= 2;
                std::cout << value << '\n';;
            }

            catch (...)
            {
                std::cout << token << '\n';
            }
        }
    }
}
you may use isdigit(variable_name); here.
Topic archived. No new replies allowed.