How would I convert a string to a float?

Having trouble converting a string to a float in main in this program. Using Visual Studio 2017. Any ideas how to proceed?

//header file: Rectangle.h

#ifndef RECTANGLE_H
#define RECTANGLE_H

class Rectangle{
private:
float length;
float width;

public:
Rectangle();
float calcPerimeter();
float calcArea();
void setLength(float length);
void setWidth(float width);

float getLength();
float getWidth();
void showData();
};

#endif

___________________________________________________

// implementation file: Rectangle.cpp
//
#include "Rectangle.h"
using namespace std;
#include<iostream>

Rectangle::Rectangle(){
this->length = 0;
this->width = 0;
}

float Rectangle::calcPerimeter(){
return 2*(this->length + this->width);
}
float Rectangle::calcArea(){
return this->length*this->width;
}
void Rectangle::setLength(float length){
this->length = length;
}

void Rectangle::setWidth(float width){
this->width = width;
}

float Rectangle::getLength(){
return this->length;
}

float Rectangle::getWidth(){
return this->width;
}

void Rectangle::showData(){
cout<<"length = "<<this->length;
cout<<", width = "<<this->width;
cout<<", perimeter = "<<this->calcPerimeter();
cout<<", area = "<<this->calcArea();

}

_______________________________________________________________

// driver file: driver.cpp
//
#include "Rectangle.h"
#include "Rectangle.cpp"
using namespace std;
//
int main(){
float len,wid;
Rectangle rect1; // instance of Rectangle (object)
string input = "";
//
while(true){
do{
cout<<endl<<"Enter length: "; cin>>input;
if(input=="Ctrl-Z"){
exit(0);
}else
len = stof(input); // string to float
}while(len<=0);
//
do{
cout<<endl<<"Enter width: "; cin>>input;
if(input=="Ctrl-Z"){
exit(0);
}else
wid = stof(input); // string to float
}while(wid<=0);
//
// setting the Rectangle properties
rect1.setLength(len);
rect1.setWidth(wid);
rect1.showData(); // display
}

return 0;
}
Last edited on
OP's code, formatted and put into code blocks:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// header file: Rectangle.h

#ifndef RECTANGLE_H
#define RECTANGLE_H

class Rectangle {
 private:
  float length;
  float width;

 public:
  Rectangle();
  float calcPerimeter();
  float calcArea();
  void setLength(float length);
  void setWidth(float width);

  float getLength();
  float getWidth();
  void showData();
};

#endif 

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
// implementation file: Rectangle.cpp
//
#include "Rectangle.h"
using namespace std;
#include <iostream>

Rectangle::Rectangle() {
  this->length = 0;
  this->width = 0;
}

float Rectangle::calcPerimeter() { return 2 * (this->length + this->width); }
float Rectangle::calcArea() { return this->length * this->width; }
void Rectangle::setLength(float length) { this->length = length; }

void Rectangle::setWidth(float width) { this->width = width; }

float Rectangle::getLength() { return this->length; }

float Rectangle::getWidth() { return this->width; }

void Rectangle::showData() {
  cout << "length = " << this->length;
  cout << ", width = " << this->width;
  cout << ", perimeter = " << this->calcPerimeter();
  cout << ", area = " << this->calcArea();
}

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
// driver file: driver.cpp
//
#include "Rectangle.cpp"
#include "Rectangle.h"
using namespace std;
//
int main() {
  float len, wid;
  Rectangle rect1;  // instance of Rectangle (object)
  string input = "";
  //
  while (true) {
    do {
      cout << endl << "Enter length: ";
      cin >> input;
      if (input == "Ctrl-Z") {
        exit(0);
      } else
        len = stof(input);  // string to float
    } while (len <= 0);
    //
    do {
      cout << endl << "Enter width: ";
      cin >> input;
      if (input == "Ctrl-Z") {
        exit(0);
      } else
        wid = stof(input);  // string to float
    } while (wid <= 0);
    //
    // setting the Rectangle properties
    rect1.setLength(len);
    rect1.setWidth(wid);
    rect1.showData();  // display
  }

  return 0;
}


You use std::stof and your code does compile for me (though you really shouldn't be #including cpp files). What issue are you having?

-Albatross
Last edited on
I get the error, 'std:stof is unidentified' Also my "cin >>" no operator matches these operands
Ah. You may need to #include <string> in your driver.cpp file.

-Albatross
That fixed the stof problem, but now I'm getting "cin" and "cout" identifiers are undefined. Just to clarify Rectangle.h should be in headers and Rectangle.cpp and Driver.cpp should be in source files correct?
Last edited on
So you need
#include <iostream>
in driver.cpp as well.
Last edited on
That fixed the "cin/cout" problem but now im getting errors saying all my public statement in Rectangle.h are already defined in Rectangle.obj
Last edited on
Maybe it's time that you posted your up-to-date code. In CODE TAGS.

You don't need
#include "Rectangle.cpp"
in driver.cpp; the prototypes are pulled in by the #include "Rectangle.h" statement.
Last edited on
OK so here is updated code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// header file: Rectangle.h

#ifndef RECTANGLE_H
#define RECTANGLE_H

class Rectangle
{
private:
	float length;
	float width;

public:
	Rectangle();
	float calcPerimeter();
	float calcArea();
	void setLength(float length);
	void setWidth(float width);

	float getLength();
	float getWidth();
	void showData();
};

#endif  

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
41
42
43
44
45
46
47
// implementation file: Rectangle.cpp

#include "Rectangle.h"
using namespace std;
#include <iostream>

Rectangle::Rectangle()
{
	this->length = 0;
	this->width = 0;
}

float Rectangle::calcPerimeter()
{
	return 2 * (this->length + this->width);
}
float Rectangle::calcArea()
{
	return this->length * this->width;
}
void Rectangle::setLength(float length)
{
	this->length = length;
}

void Rectangle::setWidth(float width)
{
	this->width = width;
}

float Rectangle::getLength()
{
	return this->length;
}

float Rectangle::getWidth()
{
	return this->width;
}

void Rectangle::showData()
{
	cout << "length = " << this->length;
	cout << ", width = " << this->width;
	cout << ", perimeter = " << this->calcPerimeter();
	cout << ", area = " << this->calcArea();
}

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
41
42
43
44
#include "Rectangle.h"
#include <string>
#include <iostream>
using namespace std;

int main() 
{
	float len, wid;
	Rectangle rect1;  // instance of Rectangle (object)
	string input = "";
	while (true);
	{
		do 
		{
			cout << endl << "Enter length: ";
			cin >> input;
			if (input == "Ctrl-Z")
			{
				exit(0);
			}
			else
				len = stof(input);  // string to float
		} while (len <= 0);
	
		do 
		{
			cout << endl << "Enter width: ";
			cin >> input;
			if (input == "Ctrl-Z")
			{
				exit(0);
			}
			else
				wid = stof(input);  // string to float
		} while (wid <= 0);
	
		// setting the Rectangle properties
		rect1.setLength(len);
		rect1.setWidth(wid);
		rect1.showData();  // display
	}

	return 0;
}


It now will launch, but nothing appears on my prompt window. When I run debug I just get a blank black screen
while (true);


Look VERY closely. Where does that loop end? And HOW DO YOU GET OUT OF IT?
doesn't
rect1.showData(); end the loop?
No, the
;
at the end of the while statement bounds the loop. And since the content of the while test is forever true ... it will repeat that line for ever!

Just remove that semicolon and leave
while (true)
Last edited on
doesn't
rect1.showData(); end the loop?
Why and how would showData() end the loop?
There are only two options: Either the condition for running the loop changes to false or you have a break; statement within the loop.
So since you have neither the loop will not end. [Apart from the wrongful ; as lastchance pointed out].
Wow can't believe I missed that... I just need to add some error checking and I'm done. Appreciate all the help!
if (input == "Ctrl-Z")
I don't think this does what you expect. It will only be true of the user types the 6 characters "C" "t" "r" "l" "-" "Z" and presses Enter. I think what you're looking for is whether they held down the CTRL key and pressed Z.

That combination (on Windows) tells the OS that the stream has ended. To test for this and other error conditions, replace if (input == "Ctrl-Z") with if (!cin)
on windows, in ascii modes, ctrlz is 26 (ascii code). But i am not sure you can actually 'read' it from cin. Its not printable...
Fixed main to accept "Ctrl-Z" to quit. Only thing I need now is error checking for not accepting letters as input.
> Only thing I need now is error checking for not accepting letters as input.

Write a function. For instance:

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

// return a positive value entered for the dimension
float get_dimension( std::string name )
{
    std::string dim ;
    while( std::cout << "enter " << name << ": " && std::cin >> dim )
    {
        try
        {
            // try to convert the input to a floating point value
            std::size_t pos = 0 ;
            const float dim_value = std::stof( dim, std::addressof(pos) ) ;

            if( pos < dim.size() ) // if the input was not fully parsed
                std::cout << "input contains invalid trailing characters. try again\n" ;

            else if( dim_value > 0 ) return dim_value ; // positive value, return it

            else std::cout << name << " must be positive. try again\n" ;
        }

        catch(...) { std::cout << "invalid input. try again\n" ; }
    }

    return 0 ; // return 0 if eof is encountered on stdin
}

int main()
{
    const float length = get_dimension( "length" ) ;
    const float width = get_dimension( "width" ) ;
    std::cout << "length: " << length << "  width: " << width << '\n' ;
}
Topic archived. No new replies allowed.