Having an issue with static cast

closed account (yR9wb7Xj)
I don't understand why the static cast is not working. This is the exact same solution from this site that I'm learning from. Why is it not working?
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
35
36
37
38
39
40
// Quiz Problem Lesson 4.4b on Learncpp.com
/*
 * 1) Write a program that asks the user to enter their full name and their age.
 *  As output, tell the user how many years they’ve lived for each letter in their name
 *  (for simplicity, count spaces as a letter).
 */

#include <iostream>
using namespace std;
int main()
{





	string name;
	string age;
	int letters = name.length();


	cout << "Enter your full name." << endl;
	getline(cin,name);

	cout << "Enter your age." << endl;
	cin >> age;

// The problem is this single line of code below.

	double agePerLetter = static_cast<double>(age) / letters;

	cout << "You've lived " << agePerLetter << " years for each letter in your name.\n"<<endl;






	return 0;
}
Last edited on
You can only cast primitive types. Why is age a string instead of an int?
closed account (yR9wb7Xj)
It still does not work.
I realize that as well, because you can't compare strings with int.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
int main()
{
 string name;
 int age;

 
 cout << "Enter your full name:" << " " << endl;
 getline(cin,name);
 
 cout << "Enter your age: " << " " << endl;
 cin >> age;
 
double agePerLetter = static_cast(age)/letters;
cout << "You've lived " << agePerLetter << " years for each letter in your name.\n"<<endl;
	return 0;
}
Last edited on
closed account (yR9wb7Xj)
Nevermind I over looked this, I see what I was missing from the provided solution on the site.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
int main()
{
 string name;
 int age;


 cout << "Enter your full name:" << " " << endl;
 getline(cin,name);

 cout << "Enter your age: " << " " << endl;
 cin >> age;

 int letters =name.length();
double agePerLetter = static_cast<double>(age)/letters;

cout << "You lived for :" << " " << agePerLetter << endl;

	return 0;
}
Topic archived. No new replies allowed.