file setprecision c++ code - c++

I had this code in C++ that is working just fine, first it ask the user for a
file name, and then saves some number in that file.
But what I am trying to do is to save numbers with two decimal places, e.g the
user types 2 and I want to save the number 2, but with two decimal places
2.00.
Any ideas of how to do that?
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
double num;
double data;
string fileName = " ";
cout << "File name: " << endl;
getline(cin, fileName);
cout << "How many numbers do you want to insert? ";
cin >> num;
for (int i = 1; i <= num; i++) {
ofstream myfile;
myfile.open(fileName.c_str(), ios::app);
cout << "Num " << i << ": ";
cin >> data;
myfile << data << setprecision(3) << endl;
myfile.close();
}
return 0;
}

Ok, you need to use setprecision before the data is written.
I would also move the open and close of the file out of the loop (and the declaration of myfile, of course, as it's generally a fairly "heavy" operation to open and close a file inside a loop like this.
Here's a little demo that works:
#include <iostream>
#include <fstream>
#include <iomanip>
int main()
{
std::ofstream f("a.txt", std::ios::app);
double d = 3.1415926;
f << "Test 1 " << std::setprecision(5) << d << std::endl;
f << "Test 2 " << d << std::endl;
f << std::setprecision(7);
f << "Test 3 " << d << std::endl;
f.precision(3);
f << "Test 3 " << d << std::endl;
f.close();
}
Note however that if your number is for example 3.0, then you also need std::fixed. E.g. if we do this:
f << "Test 1 " << std::fixed << std::setprecision(5) << d << std::endl;
it will show 3.00000

Related

meet error while trying to read int number from input file

I am new to coding C++. I meet issue while trying to read 2 int number from input file, calculate them and then export to output. System showing issue at line 14,18 and 21 of the loop. Please give me advice on this. Thanks all!
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
file.open("input.txt");
string word;
word.clear();
int a, b;
int count = 0;
while(file>>word)
{
count++;
if (count % 2 == 1){
a = stoi(word);
}
else {
b = stoi(word);
}
}
int TOTAL = a + b;
int Difference = a - b;
int Multiply = a * b;
int Division = a / b;
int MUD = a % b;
ofstream out("output.txt");
out << "Input Values: " << a << " " << b << endl;
out << "Sum of two numbers: " << TOTAL << endl;
out << "Difference of two numbers: " << Difference << endl;
out << "Multiply of two numbers: " << Multiply << endl;
out << "Division of two numbers: " << Division << endl;
out << "Modular division of two numbers: " << MUD << endl;
cout << "Calculation written in file" << endl;
out.close();
return 0;
}
#include <string> because you are using string functions that's the problem I think

Working with GPS Output using C++

Hi I'm working with GPS output. To be more accurate I'm working using the $GPRMC output. Now the output that I get is in the following form:
$GPRMC,225446,A,4916.45 N,12311.12 W,000.5,054.7,191194,020.3 E,*68"
This output constitutes of time, lats, longs, speed in knots, info about course, date, magnetic variation and mandatory checksum.
The image that I have attached shows the current result I'm getting as I'm taking out the sub strings from the string.
Now I'm getting the time in the hhmmss format. I want it in hh:mm:ss format.
Plus I'm getting the longitude as 4916.45 N. I want to get it as 49 degrees 16' 45".
And the latitude as 123 degrees 11' 12". I'm a beginner so I really don't know how to convert the format. I have also attached my code below.
#include<iostream>
#include<string>
#include<sstream>
#include<stdio.h>
#include<conio.h>
using namespace std;
int main()
{
std::string input = "$GPRMC,225446,A,4916.45 N,12311.12 W,000.5,054.7,191194,020.3 E,*68";
std::istringstream ss(input);
std::string token;
string a[10];
int n = 0;
while (std::getline(ss, token, ','))
{
//std::cout << token << '\n';
a[n] = token;
n++;
}
cout << a[0] << endl << endl;
cout << "Time=" << a[1] << endl << endl;
cout << "Navigation receiver status:" << a[2] << endl << endl;
cout << "Latitude=" << a[3] << endl << endl;
cout << "Longitude=" << a[4] << endl << endl;
cout << "Speed over ground knots:" << a[5] << endl << endl;
cout << "Course made good,True:" << a[6] << endl << endl;
cout << "Date of Fix:" << a[7] << endl << endl;
cout << "Magnetic variation:" << a[8] << endl << endl;
cout << "Mandatory Checksum:" << a[9] << endl << endl;
_getch();
return 0;
}
First thing is that your NMEA sentence is wrong, there should be commas ',' before N and W, so you will actually have to parse "12311.12" and not "12311.12 W". You can check it on this site: http://aprs.gids.nl/nmea/#rmc, you should also always check checksum of sentence - for online checks use: http://www.hhhh.org/wiml/proj/nmeaxor.html.
To parse longitude and latitude I suggest regexps, I am notsaying this is regexp is correct - it only parses data you have provided:
#include <iostream>
#include <string>
#include <regex>
#include <iostream>
std::tuple<int,int,int> parseLonLat(const std::string& s) {
std::regex pattern("(\\d{2,3})(\\d+{2})\\.(\\d+{2})" );
// Matching single string
std::smatch sm;
if (std::regex_match(s, sm, pattern)) {
return std::make_tuple(std::stoi(sm[1]), std::stoi(sm[2]), std::stoi(sm[3]));
}
return std::make_tuple(-1,-1,-1);
}
int main (int argc, char** argv) {
auto loc1 = parseLonLat("4916.45");
std::cout << std::get<0>(loc1) << ", " << std::get<1>(loc1) << ", " << std::get<2>(loc1) << "\n";
// output: 49, 16, 45
auto loc2 = parseLonLat("12311.12");
std::cout << std::get<0>(loc2) << ", " << std::get<1>(loc2) << ", " << std::get<2>(loc2) << "\n";
// output: 123, 11, 12
}
http://coliru.stacked-crooked.com/a/ce6bdb1e551df8b5
You'll have to parse that yourself; there's no GPS parsing in standard C++.
You may want to write your own Angle class in order to have 49 degrees 16' 45" as possible output. You'll want to overload operator<< for that.

I'm new to C++ and I have few questions I'd like to ask

Question is :
Please enter the number of gallons of gasoline: 100
Original number of gallons is: 100
100 gallons is the equivalent of 378.54 liters
Thanks for playing
how to display "Original number of gallons is: 100"
and my "Thanks for playing" is combined with "press any key to continue" I dont know how to seperate them.
#include <iostream>
using namespace std;
int main()
{
float g;
float l;
cout << "Please enter the number of gallons of gasoline ";
cin >> g;
l = g*3.7854;
cout << g << " Gallon is the equivalent of " << l << "liters" << endl;
cout << "Thank you for playing";
system("pause");
return 0;
}
Do not use "use namespace std;", this is bad practice.
Using system("pause") is also bad practice.
Use
std::cout << std::endl;
To output a newline, to separate different lines of text.
#include <conio.h> // Added for _getch();
#include <iostream>
// removed "using namespace std;"
int main() {
float g = 0; // Added Initialization To The Variables
float l = 0;
// From Here On Out I Will Be Using The Scope Resolution Operator To Access the std namespace.
std::cout << "Please enter the number of gallons of gasoline" << std::endl;
std::cin >> g;
l = g*3.7854f; // Added an 'f' at the end since you declared floats and not doubles
std::cout "Original number of gallon(s) is: " << g << std::endl;
std::cout << g << "Gallon(s) is the equivalent of " << l << "liter(s)" << std::endl;
std::cout << "Thank you for playing" << std::endl;
// Changed System( "pause" ); To
std::cout << "\nPress any key to quit!\n";
_getch();
return 0;
} // main
Try placing the variables outside the main.
Also, get rid of the system("pause"); and at the end of every cout, before the semicolon, add << "\n";
At the end, the code should look like this:
#include <iostream>
using namespace std;
float g;
float l;
int main()
{
cout << "Please enter the number of gallons of gasoline ";
cin >> g;
cout << "Original number of gallons is: " << g << "\n";
l = g*3.7854;
cout << g << " gallon(s) is/are the equivalent of " << l << " liters\n";
cout << "Thank you for playing\n";
return 0;
}

C++ manipulation using iomanip library

I am new to C++ STL libraries and need help.
I want to add two numbers suppose A = 4555 and B = 50, and output them as:
4555
+50
4605
Another Examples:
500000 + 12
500000
+12
500012
If i am storing both A and B in integer data type while the sign '+' in character data type. How can i manipulate them to get the preferred output.
I just cant figure out how to manipulate two variables together.
You might utilize the manipulators std::showpos, std::noshowpos and std::setw:
#include <iostream>
#include <iomanip>
int main() {
int a = 4555;
int b = 50;
std::cout
<< std::noshowpos << std::setw(10) << a << '\n'
<< std::showpos << std::setw(10) << b << '\n'
<< std::noshowpos << std::setw(10) << (a+b) << '\n';
}
If you want a width depending on the values you may use three std::ostringstream(s) and create intermediate strings (without setw). After that you print the strings using the maximal length of each for setw:
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <sstream>
int main() {
int a = 4555;
int b = 50;
std::ostringstream as;
std::ostringstream bs;
std::ostringstream rs;
as << std::noshowpos << a;
bs << std::showpos << b;
rs << std::noshowpos << (a+b);
unsigned width = std::max({ as.str().size(), bs.str().size(), rs.str().size() });
std::cout
<< std::setw(width) << as.str() << '\n'
<< std::setw(width) << bs.str() << '\n'
<< std::setw(width) << rs.str() << '\n';
}
See also:
http://www.cplusplus.com/reference/iomanip/
http://www.cplusplus.com/reference/ios/
Note: You may have a look at the manipulator std::internal.
If you could use constant width (or variable width equal to the maximum width of the numbers involved) with std::setw from <iomanip> as:
#include <iostream>
#include <iomanip>
#include <string>
void display_sum(int a, int b)
{
std::cout << std::setw(10) << a << "\n"
<< std::setw(10) << ("+" + std::to_string(b)) << "\n"
<< std::setw(10) << (a+b) <<"\n" << std::endl;
}
int main()
{
display_sum(4555, 50);
display_sum(500000, 12);
display_sum(503930, 3922);
}
Output:
4555
+50
4605
500000
+12
500012
503930
+3922
507852
Online demo
In your example the fields can fit a maximum number of 7 characters. Perhaps you want to resize the strings to 7 before writing. e.g. fname.resize(7).
To format it as you want you need to #include <iomanip> and use std::left and std::setw(7).
file1 << left << setw(7) << fname
<< tab << setw(7) << lname
<< tab << setw(7) << street
<< tab << setw(7) << city
<< tab << setw(7) << state
<< tab << setw(7) << zip << endl;

Simple c++ cout statment, one line with a formatting issue, what it is?

Here is my code:
#include <iomanip>
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
ifstream fin;
fin.open("Celsius.txt");
if (!fin.good()) throw "I/O error";
double myC;
fin >> myC;
fin.close();
ofstream fout;
fout.open("Fahrenheit.txt");
if (!fout.good()) throw "I/O error";
double myAnswer = (myC * 1.80) + 32;
fixed;
cout << myC << " Celsius equals " << setprecision(3) << myAnswer << " Fahrenheit" << endl;
fout << myC << " Celsius equals " << setprecision(3) << myAnswer << " Fahrenheit" << endl;
fout.close();
}
Ok, am I just missing some complete fundamental neuron, I seem to have some road block understanding this.
It's -2 for formatted input echo, and
It's -2 for not formatting output with one decimal digit.
Do not format the input values only the output.
fixed;
cout << myInput << " should not be formatted, but " << setprecision(3) << myOutput << " should be" << endl;
Doesn't that stay:
myInput is the unformatted input echo
and myOutput is formatted to one decimal digit?
You must include fixed in the output stream, like so:
cout << myC << " Celsius equals " << fixed << setprecision(3) << myAnswer << " Fahrenheit" << endl;
setprecision will specify the number of decimal places after the decimal. So 3 will yeild a number like 72.000, or 1 in your case will set it to 72.0