Can't write calculated resulted to file in C++

  • Comp Sci
  • Thread starter madtraveller
  • Start date
  • Tags
    C++ File
In summary, the conversation is about a user seeking help with a C++ program they are working on for a physics forum. They are encountering an error message related to memory and are unsure why. Other users suggest checking the array index and using pre-increment instead of post-increment for optimization. The conversation concludes with a discussion about the best way to calculate an exponent, with the consensus being that using a*a*a is faster than pow(a,3).
  • #1
madtraveller
28
0

Homework Statement



Dear physics forum,

I'm start learning C++ and I'm trying to program a space transform function for linearized convection-diffusion problem using Code:block
Everything was fine until I wrote calculated result into a file. When I run the program, some error message popped up which related to "memory could not be read" and std::eek:stream::sentry::sentry() in debug windows

Code:
#include <iostream>
#include <fstream> // for working with file
#include <cmath>
#include <iomanip>
#include <stdio.h>
#include <math.h>
#include <cstdlib> // for exit function

using namespace std;

// Function for calculating exponental part of transfer function //
double  expo(double dx, double celerity, double time, double dif)
{
    double result;
    result = -(dx - celerity * time );
    result = exp ( pow (result, 2.0) / ( 4.0 * dif * time ));
    return (result);
}

// Main program
int main ()
{
    // Creat a file to store the result
    ofstream outdata;
    outdata.open ("Result.txt", ios::out);

   if( !outdata ) {                                     // file couldn't be opened
      cerr << "Error: file could not be opened" << endl;
      exit(1);
   }

    outdata << "OK??" << endl;

    // Declare variables
    double  PI = 3.14159,
            u  = 1.5,
            c,
            D  = 50.0,
            diffu = 0.0,
            t,
            t0 = 0.0,
            deltat = 1.0,
            deltax = 0.5;

    // Introduce number of interval
    int     n  = 50;

    // Create an array to store results of transfer function
    double  transfer[50] = {0.0};

    // Approximate c by u
    c = 5.0/3.0 * u;

    cout << "Time" << setw (21) << "Transfer function" << endl;

    // Loop for calculating transfer function
    for (int i = 1; i <= n; i++) {
        t = t0 + deltat * i;
        transfer[i] = deltax / ( 2.0 * sqrt( PI * D * t ));         // Calculate convection part
        diffu = expo(deltax, c, t, D);                              // Calculate diffusion part
        transfer[i] = transfer [i] * diffu;                         // Put 2 parts together

        cout << setw(2) << t << setw(18) << transfer[i] << endl;    // Print out results
    }

    for (int i = 1; i <= n; ++i) {
        outdata << transfer[i] << endl;
    }

    outdata.close();

    // Terminate the program
    return 0;
}


Homework Equations



T(t,deltax) = [tex]\frac{deltax}{2\sqrt{\Pi*D*t^{3}}}*e^{-\frac{(deltax - c*t)^2}{4*D*t}[/tex]


Plz help me with this. Thank you very much for your time

Regards,

madtraveller
 
Physics news on Phys.org
  • #2
Arrays are index from 0 in C and C++. The valid indices into the array "transfer" are 0 to 49. You are setting and then accessing elements 1 to 50.
 
  • #3
Your for loop runs from i = 1 to 50, and your transfer array is declared to have 50 members.

In C and C++, arrays are zero-based, which means that the elements of your array are transfer[0], transfer[1], ..., transfer[49]. Your for loop is attempting to write to transfer[50], which is outside your array. I believe that's what is causing your problem.

Change your loop as follows
Code:
for(i = 0; i < n; i++)
{
   // body of loop
}
 
  • #4
You guys are absolutely right! This solves my problem now !

Thank you again !

Regards,
 
  • #5
Mark44 said:
Change your loop as follows
Code:
for(i = 0; i < n; i++)
{
   // body of loop
}

Even better, use
Code:
for(i = 0; i < n; ++i)
{
   // body of loop
}

In this case use of post-increment versus pre-increment doesn't really matter. However, as soon as you start using iterators, the post-increment operator can be quite expensive compared to the pre-increment operator. In C it is fairly standard to use post-increment by default, deferring the use of pre-increment as a signal that the programmer is being tricky. In C++ it is the other way around.
 
  • #6
Could you also tell me which one is better:

pow (a, 3) or a * a * a

Thanks

Have a nice day every1

madtraveller
 
  • #7
well of course a*a*a will be faster since it does not have to deal with the general case in pow(). Micro optimizing like this is rarely needed and when it does it is a last move optimization that is carefully profiled. If your you really want to optimize your code here's a few things to try to accomplish:

write better algorithms,
reduce dynamic memory (when possible),
improve access to readable/writable data,
ect..

Trying to micro optimize your code at such a level will actually cause a decrease in code readability, which is a bigger con than having a minimal optimization
 
  • #8
madtraveller said:
Could you also tell me which one is better:

pow (a, 3) or a * a * a
Unfortunately, it is a*a*a. C and C++ lack an exponentiation operator and the pow() function is a very poor substitute for it. With most compilers, pow(a,3) is equivalent to exp(3*log(a)). This is one of the two key issues that makes some Fortran programmers think that C and C++ are terrible languages for numerical programming.
 
  • #9
Thank you guys for your info.

MT
 

Related to Can't write calculated resulted to file in C++

What does it mean when I get an error saying "Can't write calculated result to file" in my C++ program?

This error typically means that there was a problem with writing data to a file in your C++ program. This could be due to a variety of reasons, such as incorrect file permissions, a full disk, or a coding error in your program.

How can I fix the "Can't write calculated result to file" error in my C++ program?

To fix this error, you will need to carefully review your code and ensure that you are properly opening and writing to the file. You should also check for any errors or exceptions that may be occurring and handle them appropriately. If the issue persists, you may need to troubleshoot the file permissions or check for any disk space limitations.

Why am I getting a "Can't write calculated result to file" error when I was able to write to the file before?

If you were previously able to write to the file without any issues, it is possible that something has changed in your program or on your system that is now causing the error. Review any recent changes you have made and check for any updates or changes to your system that may be affecting the file writing process.

Is there a specific format or syntax I need to follow when writing data to a file in C++?

Yes, there is a specific syntax that must be followed when writing data to a file in C++. This includes opening the file, writing the data, and properly closing the file. It is important to also use appropriate formatting and ensure that the data being written matches the expected format of the file.

How can I prevent the "Can't write calculated result to file" error from occurring in my C++ program in the future?

To prevent this error, you should always carefully review your code and ensure that you are handling file operations properly. This includes checking for errors and handling them appropriately, as well as properly closing the file after writing. Additionally, regularly testing and debugging your code can help identify and resolve any issues before they cause errors like this one.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
15
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
6
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
14
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
1K
  • Programming and Computer Science
Replies
6
Views
9K
Back
Top