File input value as a float?

Hello everyone. I am currently writing a code where it reads a file with information on an item. The file is formatted and each info entry is separated with spaces. I have inputFile >> variable; codes to assign each value of the record to the variable given. Each is defined with corresponding variable types. Everything is working well except for retrieving the value for price. I have the variable inputPrice which is set to be a float. When I set the price value to that variable, the decimal point isn't included. So if the value for price in the file is $754.99, it saves the value as 755 in the inputPrice variable when I need it to save as 754.99. I have tried using setprecision but it didn't work. I dont know if it was because I didnt implement it into the code correctly or something. Hopefully you guys can help me as much as possible. Thank you.
Post your code so that we can see what is happening. Also a sample input data.

When posting code, use code tags with formatted code.


[code]
formatted code goes here
[/code]


This is going to be a lot but since you asked
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;


// Struct creation for car information
struct carInfo {
	string ID;
	string Model;
	int Qty;
	double Price;
  bool Valid;

};

//Global Constant Variable for array size
const int arraySize = 100;

// Proto gets data from file and inputs into array
void getData();

// Proto for validation of structures
bool isValid();

// Proto Menu switch -> Print Valid, invalid, exit
void welcome();

// Proto Funtion that prints only valid items
void printValidItems();

// Proto Function that prints only invalid items
void printInvalidItems() {
	cout << "option 2" << endl;
	welcome();
};

// Proto Function that provideds output for any invalid menu input input
void invalidInput();

////////////////////////////////////////////////////////////////////////////////

int main() {
  
  getData();
  welcome();

	return 0;
}

/////////////////////////////////////////////////////////////////////////////////

// Def of isValid. Validates whether inputs are valid
bool isValid(string testID, string testName, int testQty, float testPrice){
  bool valid = true;
  int digit = 0;
  
  //checks if ID is valid
  for (int i = 0; i < testID.length(); i++){
    digit++;
    if (digit <= 2 && isdigit(testID[i]) == false){
      valid = false;
      cout << testID[i] << endl;
    } else if (digit > 2 && digit <= 6 && (isalpha(testID[i]) == false || testID[i] == 'O')){
      valid = false;
      cout << testID[i] << endl;  
    } else if (digit > 6 && digit <= 9 && testID[i] == 'O'){
      valid = false;
      cout << testID[i] << endl;
    }
  }
  if (digit < 9 || digit > 9){
    valid = false;
    cout << "Invalid ID length" << endl;
  }

  //Checks if Name is Valid
  digit = 0;
  for(int i = 0; i < testName.length(); i++){
    digit++;
    if (digit == 1 && !isupper(testName[i])){
      valid = false;
      cout << testName[i] << endl;
    }else if (isalpha(testName[i-1]) && isdigit(testName[i])){
      valid = false;
      cout << testName[i] << endl;
    }else if (digit > 1 && (isupper(testName[i]) && testName[i-1] != '_')){
      valid = false;
      cout << testName[i] << endl;
    }
  }

  //Checks if Quantity is Valid
  if (testQty < 0){
    valid = false;
    cout << testQty << endl;
  }

  //Checks if Price is Valid
  if (testPrice <= 0){
    valid = false;
    cout << testPrice << endl;
  }

  return valid;
}


// Def of getData function to read file.
void getData() {
	ifstream inputFile;
	ofstream errorFile;

  string inID, inName;
  int inQty;
  double inPrice;
  int carNum = 0;

  carInfo cars[arraySize];

	inputFile.open("Records.txt");
	if (!inputFile) {
		cout << "Input file not found. Quitting program." << endl;
		system("pause");
    exit (EXIT_FAILURE);
	}

  errorFile.open("Errors.txt");
  if (!inputFile) {
		cout << "Error file not found. Quitting program." << endl;
		system("pause");
    exit (EXIT_FAILURE);
	}

  while(!inputFile.eof()){
    inputFile >> inID;
    inputFile >> inName;
    inputFile >> inQty;
    inputFile >> inPrice;

    cout << inPrice << endl; //DELETE!!!!!!!!!!!!!!!!!!!!!!!!!!

    if(isValid(inID, inName, inQty, inPrice) == true){
      cars[carNum].ID = inID;
      cars[carNum].Model = inName;
      cars[carNum].Qty = inQty;
      cars[carNum].Price = inPrice;
    } else{
      errorFile << inID << " " << inName << " " << inQty << " " << inPrice << endl;
    }
    carNum++;
  }

  inputFile.close();
  errorFile.close();
}


// Def of invalid input function. Resets input value for new input
void invalidInput() {
	cout << "Invalid input. Please try again.\n" << endl;
	welcome();
}

// Def of print Valid.
void printValidItems(){
  //Print Headers
  cout << fixed << setw(15) << "ID" << setw(15) << "Model" << setw(15) << "Qty" << setw(15) << "Price" << endl;

  //Print Values
  //for(int i = 0; i < )
}

void welcome() {
  
	int option = 0;
	enum menuSelect { valid = 1, invalid = 2, exit = 3 };

	cout << "\nHello there!\nHow may I help you?\n" << endl; // introduction
	cout << "Press 1 to print valid items in Inventory\nPress 2 to print "
			"invalid items in Inventory\nPress 3 to Exit\n"
		 << endl; // gives options

	cin >> option;

	switch (option) {
	case valid:
		printValidItems();
		break;

	case invalid:
		printInvalidItems();
		break;

	case exit:
		system("clear");
		cout << "Exiting now... Until next time!\n" << endl;
    system("pause");
		break;

	default:
		invalidInput();
		break;
	}
}


its still not finished so there are a lot of test couts to see output. I have a text file called Records.txt with this in it:
12AB1P34Z Fusion_5 20 17000.00
52KDYBF64 Camry 5 15500.99
89GGTY4D5 Altima 10 19000.00
77BAQU888 CivicXl 12 18000.00
22BIGD909 Mazda_3 6 20000.00

Program outputs into a separate file the error inputs which should be the Ford Focus and the Civic Xl. So far I am only having a problem with getting the decimal point to appear when cout the price stored, but if you have any other tips it would be helpful.
Use std::fixed in combination with std::setprecision.
1
2
std::cout << std::fixed << std::setprecision(2);
std::cout << 755.0; // prints "755.00"  

EDIT: I'm being downvoted so perhaps I said something stupid. I admit I didn't run or read all the code in detail.

Just note that if you use std::setprecision without having used std::fixed before then it will count from the most significant digit rather than the decimal point, any unnecessary zeroes at the end won't get displayed, and it will use scientific notation if necessary to avoid having to show more digits than specified.

1
2
3
4
std::cout << std::setprecision(3);
std::cout << 755.00 << "\n"; // prints "755" 
std::cout << 754.99 << "\n"; // prints "755" 
std::cout << 7549.9 << "\n"; // prints "7.55e+03" (which should be read as 7.55 times 10 to the power of 3) 
Last edited on
There are issues with reading the data from the file. As a first refactor consider:

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include <fstream>
#include <iostream>
#include <iomanip>
#include <cctype>

struct carInfo {
	std::string ID;
	std::string Model;
	int Qty {};
	double Price {};
	bool Valid {};
};

const size_t arraySize { 100 };

size_t getData(carInfo cars[arraySize]);
void welcome(const carInfo cars[], size_t norec);

int main() {
	carInfo cars[arraySize] {};
	const auto norec { getData(cars) };

	welcome(cars, norec);
}

bool isValid(const std::string& testID, const std::string& testName, int testQty, double testPrice) {
	size_t digit {};

	//checks if ID is valid
	for (size_t i {}; i < testID.length(); ++i) {
		++digit;

		if (digit <= 2 && std::isdigit(static_cast<unsigned char>(testID[i])) == false)
			return false;

		if (digit > 2 && digit <= 6 && (std::isalpha(static_cast<unsigned char>(testID[i])) == false || testID[i] == 'O'))
			return false;

		if (digit > 6 && digit <= 9 && testID[i] == 'O')
			return false;
	}

	if (digit != 9)
		return false;

	//Checks if Name is Valid
	digit = 0;

	for (size_t i {}; i < testName.length(); ++i) {
		++digit;

		if (digit == 1 && !std::isupper(static_cast<unsigned char>(testName[i])))
			return false;

		if (std::isalpha(static_cast<unsigned char>(testName[i - 1])) && std::isdigit(static_cast<unsigned char>(testName[i])))
			return false;

		if (digit > 1 && (std::isupper(static_cast<unsigned char>(testName[i])) && testName[i - 1] != '_'))
			return false;
	}

	//Checks if Quantity is Valid
	if (testQty < 0)
		return false;

	//Checks if Price is Valid
	if (testPrice <= 0)
		return false;

	return true;
}

size_t getData(carInfo cars[arraySize]) {
	std::ifstream inputFile("Records.txt");

	if (!inputFile) {
		std::cout << "Input file not found. Quitting program.\n";
		exit(EXIT_FAILURE);
	}

	std::ofstream errorFile("Errors.txt");

	if (!errorFile) {
		std::cout << "Error file not found. Quitting program.\n";
		exit(EXIT_FAILURE);
	}

	size_t carNum {};

	for (carInfo car; carNum < arraySize && (inputFile >> car.ID >> car.Model >> car.Qty >> car.Price); ++carNum) {
		car.Valid = isValid(car.ID, car.Model, car.Qty, car.Price);
		cars[carNum] = car;

		if (!cars[carNum].Valid)
			errorFile << car.ID << " " << car.Model << " " << car.Qty << " " << car.Price << '\n';
	}

	return carNum;
}

void invalidInput() {
	std::cout << "Invalid input. Please try again.\n";
}

void printItems(const carInfo cars[], size_t nocars, bool valid) {
	std::cout << std::setw(15) << "ID" << std::setw(15) << "Model" << std::setw(15) << "Qty"
		<< std::setw(15) << "Price" << '\n';

	for (size_t i {}; i < nocars; ++i)
		if (valid == cars[i].Valid)
			std::cout << std::setw(15) << cars[i].ID << std::setw(15) << cars[i].Model << std::setw(15) << cars[i].Qty
			<< std::setw(15) << std::setprecision(2) << std::fixed << cars[i].Price << '\n';
}

void welcome(const carInfo cars[], size_t norec) {
	int option {};
	enum menuSelect {
		valid = 1, invalid = 2, exit = 3
	};

	while (option != exit) {
		std::cout << "\nHello there!\nHow may I help you?\n\n";
		std::cout << "Press 1 to print valid items in Inventory\nPress 2 to print "
			"invalid items in Inventory\nPress 3 to Exit\n\n";

		std::cin >> option;

		switch (option) {
			case valid:
				printItems(cars, norec, true);
				break;

			case invalid:
				printItems(cars, norec, false);
				break;

			case exit:
				break;

			default:
				invalidInput();
				break;
		}
	}

	std::cout << "Exiting now... Until next time!\n\n";
}


where option 1 displays:


            ID          Model            Qty          Price
     52KDYBF64          Camry              5       15500.99
     89GGTY4D5         Altima             10       19000.00
     22BIGD909        Mazda_3              6       20000.00

Thank you so much. I didn't exactly do the same thing you showed but thanks to having a visual of how the code should be helped me figure out the decimal problem as well as other inconveniences that I was struggling with, thank you again.
Registered users can post here. Sign in or register to post.