How do I show points for double without iomanip functions? - casting

I am on a project where the major task is to read in from a file a a character from c string at a time using .get(), and store it in a char buffer, and convert the value to double if its double value like "20.12". I've done implementation of converting to double, but I am not sure how to show point to 2 decimal points.
since we are restricted from using any function from iomanip, secprecision or showpoint is not considered.
here is my implementation of CstrToDbl
double stuCstrToDbl(const char *num)
{
double value=0.0;
double decimal=1.00;
int decimalCount=0;
double decimalDiv=1.00;
int i=0;
while(num[i]!='\0')
{
i++;
}
for(int j=i-1; j>=0; j--) {
decimalCount++;
if (num[j]=='-') {
value*=-1;
}
else if(num[j]=='.'){
for(int i=0; i < decimalCount-1; i++)
{
decimalDiv*=10.00;
}
}
else {
value += (num[j] - '0') * decimal;
decimal *= 10;
}
}
value=value/decimalDiv;
return value;
}

Related

C++ iostream encoding?

I have an input.txt and an output.txt, obviously I generate the output.txt, which for now is to write the exact same thing out, but it does not do that because of a possible encoding(?) error.
Here are pictures of the input and output:
My code looks like this:
Menu.cpp:
void Menu::kiir(){
ofstream myfile("output.txt");
if (myfile.is_open()){
myfile << sakk.toString();
}
}
The toString() method in sakktabla.cpp:
string sakktabla::toString(){
std::string eredmeny="";
int x = this->x;
int y = this->y;
for (int i = 0; i < x; i++){
for (int j = 0; j < y; j++){
eredmeny += (int)getValue(i, j);
}
eredmeny += "\n";
}
return eredmeny;
}
The getValue() method:
int sakktabla::getValue(int x, int y){
return this->_vec[x][y];
}
I don't see where you're ingesting, but you seem to be:
reading character input such as the character '2';
converting that to integer input, i.e. the integer 2;
outputting that integer, here producing an ASCII character with value 2.
Possibly the confusion is that std::string::operator+= doesn't do any sort of conversion.
You possibly want:
eredmeny += std::to_string(getValue(i, j));
std::to_string() converts a bunch of numeric types to their human-readable string counterparts.

Getting variables values from a .txt file in C++

I am writing a CFD solver in C++ but I am in the very beginning. Now I am coding a solver for the linear convection. The math is ok, working well, but I need to write also a code for reading variables from a .txt file.
My code is:
//Code for solving the convection linear equation from Navier-Stokes
#include <iostream>
using namespace std;
int main()
{
float endtime=0.3; //simulation time
float dx=0.025; //element size
float xmax=2; //domain size
float c=1; //wave velocity
float C=0.3; //Courant-Friedrich-Lewy number
float dt=C*dx/c; //defining timestep by the Courant equantion
int nx=xmax/dx + 1; //defining number of elements
int nt=endtime/dt; //defining number of time points
float u[nx] = { }; //defining an initial velocity array.
float un[nx] = { };
for(int i = 4; i <= 9; i++) //defining contour conditions
{
u[i] = 2;
}
for(int n=1; n<=nt; n++)
{
std::copy(u, u + nx, un);
for(int i=1; i<=nx; i++)
{
u[i] = un[i] - c*(dt/dx)*(un[i]-un[i-1]);
}
}
for (int i = 0; i <= nx; i++)
{
cout << u[i] << endl;
}
return 0;
}
I need to take these variables values from a .txt, like the end time, element size, etc. Then, I have a .txt called "parameters", which is exactly written like that:
endtime=0.3
dx=0.025
xmax=2
c=1
C=0.3
What's the most effiecient way to get these variables values from this .txt and use it in the code?
Using only standard features:
#include <iostream>
#include <tuple>
using namespace std;
tuple<bool, string, string> read_one_value(istream& in)
{
string name;
if(getline(in, name, '='))
{
string value;
if(getline(in, value))
{
return make_tuple(true, name, value);
}
}
return make_tuple(false, "", "");
}
int main()
{
for(auto val = read_one_value(cin); get<0>(val); val = read_one_value(cin))
{
std::cout << get<1>(val) << " -> " << get<2>(val) << '\n';
}
return 0;
}
This leaves converting from the value string objects to the needed type as an exercise for the reader, and assumes your format of name=value is consistent.

Extract integer from string

I am new to C++ strings and vectors and would like to know what the issue with this code is, I was provided a vector input of strings in the form "a/b+c/d" and had to print a vector in "e/f" for where a, b, c, d are integers and e/f is in the reduced fraction form. Please help as I want to learn concept of strings properly and shift to C++ from C
vector< string > reducedFractionSums(vector < string > expressions) { int a[4]={0,0,0,0}; vector < string > results;
vector < string > results;
for(int i=0;i<expressions.size();i++){
int tmp=0;
int count=0;
for(int j=0;j<expressions[i].length();j++){
if(isdigit(expressions[i][j])){
tmp=expressions[i][j];
tmp=tmp-48;
a[count]=a[count]*10 + tmp;
}
else
count++;
}
int min=a[0];
for(int i=1;i<4;i++){
if(a[i]<min){
min=a[i];
}
}
int e,f,g=1; //g for GreatestCommonDivisor
f=a[1]*a[3];
e=(a[0]*a[3])+(a[2]*a[1]);
for(int i=1;i<=min;i++){
if(e%i==0 && f%i==0){
g=i;
}
}
e=e/g;
f=f/g;
results.push_back(e + "/" + f);
}
return results;
}
int main(){
vector < string > input;
vector < string > output;
int t;
cin>>t;
while(t--){
string s;
cin>>s;
input.push_back(s);
}
output=reducedFractionSums(input);
for(int i = 0;i<output.size();i++){
cout<<output.at(i);
}
return 1;
}
Use std::stoi to convert Single integer from string, std::to_string to convert integer to string and __gcd to calculate GCD which is defined in algorithm header file to find reduced form of fraction.
#include <bits/stdc++.h>
using namespace std;
vector<int>reduced_fraction(vector<int>v) // Function to find reduced fraction form
{
int num = v[0]*v[3]+v[1]*v[2]; // numerator = a*d+b*c
int den = v[1]*v[3]; // denominator = b*d
int gcd = __gcd(num,den); // gcd = gcd(greatest common divisor) of numerator and denominator
num/=gcd; // num/den = e/f(reduced fraction)
den/=gcd;
vector<int>frac;
frac.push_back(num);
frac.push_back(den);
return frac;
}
int main() {
string s,st;
vector<string>fr; // vector to store strings of form a/b+c/d
int n=2; //Number of Strings
for(int i=0;i<n;i++)
{
cin>>s;
fr.push_back(s);
}
for(int i=0;i<n;i++)
{
s=fr[i];
vector <int>v,red_frac;
while(s.compare("")!=0)
{
if(s.at(0)=='/' || s.at(0)=='+')
s.erase(0,1);
else
{
st=to_string(stoi(s)); // fetch integer from string
v.push_back(stoi(s));
s=s.erase(0,st.length()); // remove integer from string
}
}
red_frac=reduced_fraction(v); // red_frac->reduced fraction
cout<<red_frac[0]<<"/"<<red_frac[1]<<endl;
}
return 0;
}
Input:
14/2+9/6
8/4+5/4
Output:
17/2
13/4
Ideone Link

C++ 2d read-in array troubles

I need help with reading in a text file that has string integers for the first row and for the first column. I need to have everything print out in a table format. The program I have reads in a edited text file that only has the floats, and works fine. The program is meant to read in the text file, find the average and totals for each row and column, and print it all out in a table, but I'm unsure how to go about this. The table is supposed to print like so:
Department-Name Electric Copier Phone Miscellaneous sumOfRows totalOfRows
Bookkeeping 434.92 233.76 322.25 1442.98
Sales 610.55 233.21 144.75 1232.20
Service 343.21 224.76 128.90 987.00
Customer Relations 278.23 98.43 177.34 899.32
Marketing 522.32 109.78 233.45 1232.45
Media 132.98 221.43 119.56 1090.30
Human-Resources 109.56 342.87 298 1154
sumOfColumns
totalofColumns
I was told that I could input two string arrays, one for the first row and one for the first column, but I'm unsure how I could print it out in a table format.
Here is the file:
Department-Name Electric Copier Phone Miscellaneous
Bookkeeping 434.92 233.76 322.25 1442.98
Sales 610.55 233.21 144.75 1232.20
Service 343.21 224.76 128.90 987.00
Customer Relations 278.23 98.43 177.34 899.32
Marketing 522.32 109.78 233.45 1232.45
Media 132.98 221.43 119.56 1090.30
Human-Resources 109.56 342.87 298 1154
Here is my code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
const int ROWSPACE = 7;
const int COLUMNSPACE = 4;
float rowAverage[ROWSPACE] = {0};
float colAverage[COLUMNSPACE] = {0};
float rowTotal[ROWSPACE] = {0};
float colTotal[COLUMNSPACE] = {0};
float getAverage(float averageArray[][COLUMNSPACE], int size, float rowAverage[], float colAverage[]);
float calcTotal(float sumArray[][COLUMNSPACE], int sz, float rowTotal[], float colTotal[]);
void getData(float expense[][COLUMNSPACE], int ROWSPACE);
void printTable();
int _tmain(int argc, _TCHAR* argv[])
{
printTable();//Prints the data.
system("pause");
return 0;
}
float getAverage(float averageArray[][COLUMNSPACE], int size, float rowAverage[], float colAverage[])//Finds the sums of the rows and columns.
{
int i,j;
float sum = 0, average;
cout<<"These are the row averages: \n";
for(i = 0; i<size; i++)
{
for(j=0; j<COLUMNSPACE; j++)
{
sum+=averageArray[i][j];//Finds the overall average
rowAverage[i] += averageArray[i][j]; //Finds each row's average
colAverage[j] += averageArray[i][j]; //Finds each column's average.
}
rowAverage[i] /= COLUMNSPACE;
cout<<rowAverage[i]<<"\t"; //prints the row averages
}
cout<<endl;
cout<<"These are the column averages: \n";
for(j=0; j<COLUMNSPACE; j++)
{
colAverage[j] /= size;
cout<<colAverage[j]<<"\t"; //prints the column averages
}
average=sum/(size * COLUMNSPACE);
return average;
}
float calcTotal(float sumArray[][COLUMNSPACE], int sz, float rowTotal[], float colTotal[])
{
int i,j;
float sum = 0, total;
cout<<"These are the row totals: \n";
for(i = 0; i<sz; i++)
{
for(j=0; j<COLUMNSPACE; j++)
{
sum+=sumArray[i][j]; //Finds the overall total
rowTotal[i] += sumArray[i][j]; //Finds the row totals
colTotal[j] += sumArray[i][j]; //Finds the column totals
}
cout<<rowTotal[i]<<"\t"; //prints out row totals
}
cout<<"\nThese are the column totals: \n";
for(j=0; j<COLUMNSPACE; j++) {
cout<<colTotal[j]<<"\t"; //Prints out column totals
}
total=sum;
return total;
}
void getData(float expense[][COLUMNSPACE], int ROWSPACE)
{
ifstream expenseFile;
ofstream outFile;
int i, j;
expenseFile.open("Expense1.txt"); //reads in the file (I have Expense1 as the floats only, and Expense with the strings and the floats)
outFile.open("newFile.txt"); //creates thew new file
outFile<<"The expenses are: \n";
for(i = 0; i<ROWSPACE; i++) //creates the array from the file
{
for(j = 0; j<COLUMNSPACE; j++)
{
expenseFile>>expense[i][j];
cout<<expense[i][j]<<"\t";
outFile<<expense[i][j]<<"\t";
}
cout << endl; //closes the expense file
outFile << endl; //closes the new file
}
}
void printTable() //prints out the data
{
float average;
float total;
float expenseArray[ROWSPACE][COLUMNSPACE];
cout<<"Electric Copier Phone Miscellaneous\n";
getData(expenseArray,ROWSPACE);
cout<<endl;
average=getAverage(expenseArray,ROWSPACE,rowAverage, colAverage);
cout<<endl;
total= calcTotal(expenseArray, ROWSPACE, rowTotal, colTotal);
cout<<endl;
}
Any suggestions?
Use an array of structures, not a 2D array.
One reason is all elements of an array must have the same data type so you can't mix strings and floats without playing shifty games with casting or unions. But with a class or structure... You can really have fun!
struct datastruct
{
string DepartmentName;
float Electric;
float Copier;
float Phone;
float Miscellaneous;
};
If allowed, prefer std::vector
std::vector<datastruct> list;
If bound by odd requirements and you have to use an array
datastruct list[ROWSPACE];
Now you can read the file in line by line. The following is adapted from Read file line by line
std::string line;
std::getline(infile, line); // discard first line. It is only header information
while (std::getline(infile, line))
{
std::istringstream iss(line);
datastruct temp;
if (!(iss >> temp.DepartmentName
>> temp.Electric
>> temp.Copier
...))
{
// handle error
}
// store temp in vector or array
list.push_back(temp);
// or
list[index] = temp;
}
If using an array add an exit condition to the while loop to prevent overrunning the end of the array
When you have a good grasp on C++ you can also overload >> for the structure and write something more like
datastruct temp;
while (infile >> temp))
{
// store temp in vector or array
}
But I'm not going to cover that trick here.
Passing it around is much easier because you now have a one dimensional vector or array.
float getAverage(vector<datastruct> & list,
vector<float> &rowAverage,
datastruct & colAverage)
or
float getAverage(datastruct list[],
int size,
float rowAverage[],
datastruct & colAverage)
To make computing the row and column average easy we modify datastruct
struct datastruct
{
string DepartmentName;
float Electric;
float Copier;
float Phone;
float Miscellaneous;
float getAverage()
{
return (Electric + Copier + phone + Miscellaneous) / 4;
}
datastruct & operator+=(const datastruct & rhs)
{
Electric += rhs.Electric;
Copier+= rhs.Copier;
Phone+= rhs.Phone;
Miscellaneous+= rhs.Miscellaneous;
return *this;
}
datastruct & operator/=(float divisor)
{
Electric /= divisor;
Copier/= divisor;
Phone/= divisor;
Miscellaneous/= divisor;
return *this;
}
};
and call it like
for (auto & row: list)
{
rowAverage.push_back(row.getAverage());
colAverage += row;
}
colAverage /= size;
or
for(i = 0; i<size; i++)
{
rowAverage[i] = list[i].getAverage();
colAverage += list[i];
}
colAverage /= size;
Here colAverge is used to sum up all the items in the list with the overloaded += operator and is then divided by the size with the/= operator.
Note that colAverage needs to be zeroed before it can be used to sum. You may want to add a method or a constructor to do that for you.
Calculating the totals is similar.

Summing Large Numbers

I have being doing some problems on the Project Euler website and have come across a problem. The Question asks,"Work out the first ten digits of the sum of the following one-hundred 50-digit numbers." I am guessing there is some mathematical way to solve this but I was just wondering how numbers this big are summed? I store the number as a string and convert each digit to a long but the number is so large that the sum does not work.
Is there a way to hold very large numbers as a variable (that is not a string)? I do not want the code to the problem as I want to solve that for myself.
I was just wondering how numbers this big are summed?
You can use an array:
long LargeNumber[5] = { < first_10_digits>, < next_10_digits>....< last_10_digits> };
Now you can calculate the sum of 2 large numbers:
long tempSum = 0;
int carry = 0;
long sum[5] = {0,0,0,0,0};
for(int i = 4; i >= 0; i--)
{
tempSum = largeNum1[i] + largeNum2[i] + carry; //sum of 10 digits
if( i == 0)
sum[i] = tempSum; //No carry in case of most significant digit
else
sum[i] = tempSum % 1000000000; //Extra digits to be 'carried over'
carry = tempSum/1000000000;
}
for( int i = 0; i < 5; i++ )
cout<<setw(10)<<setfill('0')<<sum[i]<<"\n"; //Pad with '0' on the left if needed
Is there a way to hold very large numbers as a variable (that is not a
string)?
There's no primitive for this, you can use any data structure (arrays/queues/linkedlist) and handle it suitably
I am guessing there is some mathematical way to solve this
Of course! But,
I do not want the code to the problem as I want to solve that for myself.
You may store the digits in an array. To save space and increase performance in the operations, store the digits of the number in base 10^9. so a number
182983198432847829347802092190
will be represented as the following in the array
arr[0]=2092190
arr[1]=78293478 arr[2]=19843284 arr[3]=182983
just for the sake of clarity, the number is represented as summation of arr[i]*(10^9i)
now start with i=0 and start adding the numbers the way you learnt as a kid.
I have done in java, Here I am taking to numbers N1 and N2, And I have create an array of size 1000. Lets take an example How to solve this, N1=12, N2=1234. For N1=12, temp=N1%10=2, Now add this digit with digit N2 from right to Left and store the result into array starting from i=0, similarly for rest digit of N1. The array will store the result but in reverse order. Have a looking on this link. Please check this link http://ideone.com/V5knEd
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception {
Scanner scan=new Scanner(System.in);
int A=scan.nextInt();
int B=scan.nextInt();
int [] array=new int[1000];
Arrays.fill(array,0);
int size=add(A,B,array);
for(int i=size-1;i>=0;i--){
System.out.print(array[i]);
}
}
public static int add(int A, int B, int [] array){
int carry=0;
int i=0;
while(A>0 || B>0){
int sum=A%10+B%10+carry+array[i];
array[i]=sum%10;
carry=sum/10;
A=A/10;
B=B/10;
i++;
}
while(carry>0){
array[i]=array[i]+carry%10;
carry=carry/10;
i++;
}
return i;
}
}
#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
struct grid{
int num[50];
};
int main()
{
struct grid obj[100];
char ch;
ifstream myfile ("numbers.txt");
if (myfile.is_open())
{
for(int r=0; r<100; r++)
{
for(int c=0; c<50; c++)
{
myfile >> ch;
obj[r].num[c] = ch - '0';
}
}
myfile.close();
int result[50],temp_sum = 0;
for (int c = 49; c>=0; c--)
{
for (int r=0; r<100; r++)
{
temp_sum += obj[r].num[c];
}
result[c] = temp_sum%10;
temp_sum = temp_sum/10;
}
string temp;
ostringstream convert;
convert << temp_sum;
temp = convert.str();
cout << temp_sum;
for(unsigned int count = 0; count < (10 - temp.length()); count++)
{
cout << result[count];
}
cout << endl;
}
return 0;
}
This the best way for your time and memory size :D
#include <iostream >
#include <climits >
using namespace std;
int main()
{
unsigned long long z;
cin >>z;
z=z*(z+1)/2;
C out << z;
return 0;
}