How to get this to print to the outfile? (c++) - c++

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() {
bool done = false;
cout << setprecision(20) << endl;
ifstream infile("in.txt");
ifstream outfile("out.txt");
while(!infile.eof()) {
int sign = 1;
double pi = 0;
long n;
infile >> n;
for(long i = 1; i < n; i += 2) {
pi += sign/(double)i;
sign = -sign;
}
pi *= 4;
cout << "value of pi for n = " << n << " is " << pi << endl;
}
return 0;
}
This reads from a file and prints to the console but I can't get the code to print to the outfile. I've tried doing
outfile<< "value of pi for n = " << n << " is " << pi << endl;
But that doesn't seem to work

It does not write to the file because you defined outfile as an std::ifstream
ifstream is for input files.
Define it as an ofstream and it should work.
Example:
ofstream outfile("out.txt");

Related

C++ standard deviation

#include <stdio.h> /* printf, scanf, puts, NULL */
#include <iostream> /* cin and cout functions */
#include <cmath> /*for power function etc.. */
#include <string> /*to let us use strings as inputs */
#include <sstream> /*allows conversion of strings to floats */
#include <fstream> /*has all the file input functions */
#include <cmath>
using namespace std; /*saves some typing*/
int main()
{
string Myline; //this will contain the data read from the file
ifstream myfile("StatNum2.txt"); //associate file with the input stream, note file must be in project directory with cpp file.
//need to put in correct filename in place of Filename.***
int n = 0;
float numPoints = 0.0;
int Points[200];
// Normal comment
/* Multi-line comment */
if (myfile.is_open())
{
cout << "File is open" << endl;
while (!myfile.eof()) //note the ! this means this loops reads through until the file closes
{
getline(myfile, Myline); //this reads a single line from myfile into Myline
stringstream convert(Myline);
if (!(convert >> Points[n])) //uses stringstream to convert Myline (which is a string) into a number and put it into an index of Points
{
Points[n] = 0;
}
cout << n;
cout << ' ';
cout << Points[n] << endl;
n++;
}
myfile.close();
numPoints = n;
cout << "Number of integers: " << numPoints << endl;
}
else
{
cout << "Could not open file" << endl;
}
int sum = 0.0;
for (int i = 0; i < numPoints; i = i + 1)
{
// Code here will be repeated as long as 'i' is less than 100.
sum = sum + Points[i];
}
cout << "Sum: " << sum << endl;
float average = sum / numPoints;
cout << "Average: " << average << endl;
int x = 0;
float sqdiff = 0.0;
for (int x = 0; x < numPoints; x = x + 1);
{
sqdiff = (Points[x] - average)*(Points[x] - average);
}
cout << "difference of squares:" << sqdiff << endl;
float stddev = sqrt(sqdiff/n);
cout << "Standard Deviation:" << stddev << endl;
I'm trying to find the standard deviation but am having some problems with the above code from line 65. The code produces the wrong result or says the Points[x] is undefined so not sure how to fix that
any help would be appreciated, thanks

Big values in C++

I'm doing a fibonacci and I want to save all the numbers in a .txt, i have done the code but when the cicles gets big values the program express it as an exponential, and then gets bigger as .INF.
How I can save the entry number?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ofstream File;
File.open("fibo.txt");
double val0 = 0, val1 = 1, i = 0, n, out;
cout << "Enter n of Fibonacci(n): ";
cin >> n;
while (i < n) {
if (n == 0) {
File << i << "- " << 0 << endl;
i++;
}
else {
out = val0 + val1;
val0 = val1;
val1 = out;
i++;
File << i << "- " << val0 << endl;
}
}
File.close();
return 0;
}
You can use boost::multiprecision, it's very intuitive and easy to use. Your code can be modified by changing (only) a couple of lines:
#include <boost/multiprecision/cpp_int.hpp> // need this
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
using namespace boost::multiprecision;
int main()
{
ofstream File;
File.open("fibo.txt");
cpp_int val0 = 0, val1 = 1, out; // arbitrary precision integers
int i = 0, n;
cout << "Enter n of Fibonacci(n): ";
cin >> n;
while (i < n) {
if (n == 0) {
File << i << "- " << 0 << endl;
i++;
}
else {
out = val0 + val1;
val0 = val1;
val1 = out;
i++;
File << i << "- " << val0 << endl;
}
}
File.close();
return 0;
}

Loading Variable from a file

AT
4
5
6
7
#include<iostream>
#include<stdio.h>
#include <fstream>
using namespace std;
int main()
{
int data[4], a, b, c, d, e, f;
ifstream myfile;
myfile.open("tera.txt");
for (int i = 0; i < 4; i++)
{
myfile >> data[i];
}
myfile.close();
a = data[0];
b = data[1];
c = data[2];
d = data[3];
cout << a << "\t" << b << "\t" << c << "\t" << d << "\n";
return 0;
}
it takes AT also and give garbage value. how and where should i use ignore function to ignore AT Value.
And there is one thing more if there is another array given BT containing some value like this:
AT BT
how to store BT's all values under it in an array?
You just have to skip the first line. You can also add optional error handling, otherwise read may fail for all line.
if (!myfile)
{
cout << "can't open\n";
return 0;
}
string temp;
myfile >> temp;
cout << "first line: " << temp << endl;
for (int i = 0; i < 4; i++)
{
myfile >> data[i];
if (myfile.fail())
{
cout << "error\n";
myfile.clear();
myfile.ignore(1000000, '\n');
}
}

Confused about taking file name from command line and stuff to it C++

My problem is that I cant get the getting the filename from the command line from the user, then using that filename to write the median, mode, and average. Im new to c++ so any tips or code fix would be great, and if you guys see anything else wrong please let me know, this is what I have, Im 99% done with it its just this filewriting thats giving me problems. Thank you
#include <iostream>
#include <fsteam>
#include <string>
using namespace std;
double Median(int [], int);
double Average(int [], int);
double Mode(int [], int);
int main(int argc, char *argv[])
{
ofstream outFile;
string filename = argv[1];
outputFile.open(filename.c_str());
if(!outFile)
{
cerr << "Error with the file.";
}
else
{
continue;
}
int *array;
int array_size;
cout << "How many students were surveyed? " << endl;
cin >> array_size;
if(array_size < 1)
{
cout << "Number of students surveyed must be greater than 1." << endl;
return(1);
}
else
{
array = new int [array_size];
}
cout << "Enter the number of movies each studen saw." << endl;
for(int i = 0; i < array_size; i++)
{
cout << "Student " << i+1 << ": " << endl;
cin >> array[i];
}
for(int i = 0; i < array_size; i++)
{
for(int j = i+1; j < array_size-1; j++)
{
if(array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
double median = Median(array, array_size);
double average = Average(array, array_size);
double mode = Mode(array, array_size);
outFile << "Median: " << median << endl;
outFile << "Average: "<< average << endl;
outFile << "Mode: " << mode << endl;
return 0;
}
double Median(int arr[], int size)
{
double middle;
if(size%2 == 0)
middle = (arr[size/2] + arr[size/2-1])/2;
else
middle = arr[size/2];
return middle;
}
double Average(int arr[], int size)
{
double ave = 0;
for(int i = 0; i < size ; i++)
ave += arr[i];
ave = ave/size;
return ave;
}
double Mode(int arr[], int size)
{
int count, mode = 0;
for(int i = 0; i < size; i++)
{
count = 1;
while(arr[i] == arr[i+1])
{
count++;
i++;
}
if(count > mode)
mode = arr[i];
if(count > 1)
i--;
}
return mode;
}
You'll likely see something about this in the compiler, but I'll let you know anyways #include <fsteam> is <fstream>
I'm confused as to why you chose to put this
else
{
continue;
}
instead of nothing, since continue; just jumps to the end of the current iteration, which doesn't seem necessary here.
The rest of it seems fine. It's formatted to be easily read. If you have any errors post-testing, let me know.
EDIT: Sorry, I can't add comments yet, but in response to your comment, it's likely because of what I noted about <fstream> above. It's just a typo.
I tried it with following patch.
--- orig.cpp 2014-05-17 12:39:37.000000000 +0800
+++ new.cpp 2014-05-17 12:38:28.000000000 +0800
## -1,5 +1,5 ##
#include <iostream>
-#include <fsteam>
+#include <fstream>
#include <string>
using namespace std;
## -16,13 +16,13 ##
outputFile.open(filename.c_str());
- if(!outFile)
+ if(!outputFile)
{
cerr << "Error with the file.";
}
else
{
- continue;
+// continue;
}
## -64,9 +64,9 ##
double median = Median(array, array_size);
double average = Average(array, array_size);
double mode = Mode(array, array_size);
- outFile << "Median: " << median << endl;
- outFile << "Average: "<< average << endl;
- outFile << "Mode: " << mode << endl;
+ outputFile << "Median: " << median << endl;
+ outputFile << "Average: "<< average << endl;
+ outputFile << "Mode: " << mode << endl;
return 0;
}
I think that as following.
first, You type incorrectly with fsteam -> fstream.
second, you type incorrectly with outFile -> outputFile.
third, you must don't use continue without loop.
As result, I suggest you have more focus about typing error.
Better to check the count command line arguments.
int main(int argc, char *argv[])
{
if(argc <2 )
{
cout << "Specify out file name as command line argument";
return 0;
}
. . . . .
. . . . .
}
for more details,
http://www.cprogramming.com/tutorial/c/lesson14.html

copying the actual values of a 2d array to another 2d array c++

I'm new to c++ and ive Been trying to wrap my head around this all day. I am trying to read a data file that contains an unknown amount of rows (teacher said wont be more than 100 rows though). Each row contains 4 integers whose values range from 0-100. The 4 columns represent student test scores over the course of a semester. Each line/row represents one student's scores. while each column represents 1 test. I am to set up a 2D array to read the scores into. The scores from the data file go into the first 4 columns and the average of all 4 tests calculated in column 5 for each student/row. I will have rows 0 through n-1 due to the fact that i dont know how many students/rows are in the file. On the nth row i calculate each position row[0 through 4] as the average of the entire column above it. The average grade of all the students calculated at the bottom of each column row(nth) and each students average for all four tests calculated in column 5. The average each students test average calculated at the bottom of column 5 (grades[nth row][5] ={average of all rows in column 5}
Im sure a little broader knowledge base would be extremely beneficial, but this was a homework assignment so i had to try. I think pointers would have been the most beneficial thing to understand for this assignment; however, i just havent gotten there yet.
This was my first attempt:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <sstream>
#include <cmath>
#include <vector>
using namespace std;
double grades [100][5] = {0};
int row = 0;
int column = 0;
int main() {
char line[100];
ifstream myfile("sturec.dat");
if(myfile){
while (getline(myfile, line)) {
if (line == char) {
//grades[row][column] =
cout << line << endl;
for (int i = 0; i <= line.length(); i++) {
if (line[i] != line[0]) && (i == " ") && (line[i+1] == char) {
column += 1;
}
else if (line[i] && line[i+1] && line[i+2] !== " ") {
grades[row][column] = {line[i] + line[i+1] + line[i+2]};
else if (line[i] && line[i+1] !== " " ) {
grades [row][1] = {line[i] + line[i+1]};
}
}
row += 1;
}
}
}
}
which i gave up on and started over with trying to create a vector of vectors to populate with the file. It took me a long time to figure out how to actually bring the data in from the file. Finally i resorted to:
#include //all the necessary libraries
using namespace std;
double grades[100][5] = {0}//the 2d array i had hoped to populate with the data from file
int main(){
ifstream myfile("filename");
rowCount = 0;
int t1, t2, t3, t4;
while(myfile >> t1 >> t2 >> t3 >> t4){
cout << t1 << " " << t2 << " " << t3 << " " << t4 << endl;
cout << "this is row 1 + : " << rowCount << endl;
//at this point i was just happy to have successfully read the file and printed the values.
rowCount ++;
}
for(int i = 0; i < 4; i++){
grades[rowCount][i]// this is where i got lost i tried multiple different things in attempt to populate "grades" by trying to create temp arrays to hold the values of t1,2,3,4 in order to parse them and place them in "grades", but to no avail. Any direction would be appreciated.
}
just to show some of my different approaches, i'll post the slightly different versions of similar code that i have.
``
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
double grades[100][5] = {0};
int main() {
ifstream myfile("sturec.dat");
int rowCount = 0;
int tempArray[100][4] = {0};
char test [4] = {0};
int i = 0;
while (myfile >> tempArray[rowCount][i]) {
cout << rowCount << endl << " " << i << endl;
cout << "temp array: " << tempArray<< endl;
while(i < 4){
i++;
rowCount++;
}
}
/*for (int c = 0; c <= rowCount; c++) {
for (int r = 0; r <= i; r++) {
grades[rowCount][i] = (tempArray[r][c]);
}
}
cout<< tempArray << endl << grades << endl;
*/
}
/*double final;
while (myfile >> grades[rowCount][test]) {
//cout << t1 << " " << t2 << " " << t3 << " " << t4 << endl;
cout << grades << endl;
cout << rowCount << endl;
//cout << grades[rowCount][]
rowCount ++;
}
}
*/
next
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
double grades[100][5] = {0};
int main() {
ifstream myfile("sturec.dat");
int rowCount = 0;
int tempArray[100] = {0};
int t1, t2, t3, t4;
while (myfile >> t1 >> t2 >> t3 >> t4) {
cout << t1 << " " << t2 << " " << t3 << " " << t4 << endl;
int test [4] = {0};
for (int i = 0; (i < sizeof(test) - 1); i++) {
grades[rowCount][i] = {tempArray};
}
}
double final;
while (myfile >> grades[rowCount][i]) {
cout << grades << endl;
cout << rowCount << endl;
//cout << grades[rowCount][]
rowCount ++;
}
vector < vector <int> > grades(100);
//vector <int> rows(4/*,0*/); // assigns 4 columns to rows vector with value of zero
//rows.assign(5,0);
int row = 0;
myfile.open("sturec.dat", ios::in); //opens file
if (myfile.is_open()) {
cout << "file opened" << endl;
string line;
vector<string> myLines;
while (getline(myfile, line)) { //gets lines using myfile and puts them in line
myLines.push_back(line);
cout << "string line contains: " << line << endl;
for (int columns = 0; columns <= 4 /*sizeof(rows)*/; columns ++) {
myfile >> grades[row][columns]; cout << "2" << endl;
}
row += 1;
}
}
else cout << "cannot open file" << endl;
myfile.close(); cout << "closed file" << endl;
return 0;
//cout << grades;
}
last one:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
ifstream myfile;
vector < vector <int> > grades(100);
//vector <int> rows(4/*,0*/); // assigns 4 columns to rows vector with value of zero
//rows.assign(5,0);
int row = 0;
myfile.open("sturec.dat", ios::in); //opens file
if (myfile.is_open()) {
cout << "1" << endl;
cout << "file opened" << endl;
string line;
vector<string> myLines;
while (getline(myfile, line)) { //gets lines using myfile and puts them in line
myLines.push_back(line);
cout << "string line contains: " << line << endl;
for (int columns = 0; columns <= 4 /*sizeof(rows)*/; columns ++) {
myfile >> grades[row][columns]; cout << "2" << endl;
}
row += 1;
}
}
else cout << "cannot open file" << endl;
myfile.close(); cout << "closed file" << endl;
return 0;
//cout << grades;
}
This one actually got me the first line of the file but i couldnt get this error to go away:
Run Command: line 1: 13531 Segmentation fault: 11 ./"$2" "${#:3}"
vector < vector <int> > grades(100);
initializes a vector containing 100 vector<int>s of size 0. To avoid the segmentation fault in your last example, you should either initialize this as
vector < vector <int> > grades(100,vector<int>(5,0));
or replace myfile >> grades[row][columns]; with something like
int tmp;
myfile >> tmp;
grades[row].push_back(tmp);