Program 13

Getting error when trying to compile

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

using namespace std;

int main()
{

   constexpr double cm_per_inch=2.54;

   double length=1;
   char unit=' ';

   cout<<"Please enter a length followed by a unit (c or i):\n";
   cin>>length>>unit;

   if(unit == 'i')
         cout<<length<<"in == "<<cm_per_inch*length<<"cm\n";
   else if (unit == 'c')
           cout<<length<<"cm == "<<length/cm_per_inch<<"in\n";
   else
           cout<<"Sorry, I don`t know a unit called ' "<<unit<<" '\n";

}
    
could you post what error are you getting? Seems to work fine as you have it for me
Documents/values2.cpp: In function ‘int main()’:
Documents/values2.cpp:11:4: error: ‘constexpr’ was not declared in this scope
constexpr double cm_per_inch=2.54;
^
Documents/values2.cpp:11:14: error: expected ‘;’ before ‘double’
constexpr double cm_per_inch=2.54;
^
Documents/values2.cpp:20:34: error: ‘cm_per_inch’ was not declared in this scope
cout<<length<<"in == "<<cm_per_inch*length<<"cm\n";
^
Documents/values2.cpp:22:43: error: ‘cm_per_inch’ was not declared in this scope
cout<<length<<"cm == "<<length/cm_per_inch<<"in\n";
^
constexpr was introduced in C++11 - perhaps your compiler is using an earlier standard.
constexpr is a keyword in c++11... your compiler is probably not following that standard. Change the settings for it to follow the c++11 standard and your program will compile

and btw its a bit redundant to have char unit = ' '; in line 14
char unit;would suffice
Last edited on
It is not redundant, as the input may fail before assigning value to unit.
Hm, I searched a bit the compiler issue and found this: https://gcc.gnu.org/onlinedocs/gcc/Standards.html

There is said

To select this standard in GCC, use the option -std=c++11; to obtain all the diagnostics required by the standard, you should also specify -pedantic (or -pedantic-errors if you want them to be errors rather than warnings).

Now what I should actually do is unclear...
Topic archived. No new replies allowed.