How to get rid of the last line

Hi..Im currently developing a program that will store voltage N current into an csv file..In my program,when the user inputs -100 for voltage it will terminate the program..However,in the output csv file, the value -100 appears as well..I dont want it to appear on my csv file..How do I get rid of this last row(the row with voltage=-100) in my csv file? Here is my code :


#include <iostream>
#include <fstream>
#include<string>
#include <iomanip>
using namespace std;
int main()
{
float a,b,c,d;
ifstream indata;
ofstream outdata;
outdata.open("out.csv", ios::app);
outdata << "Voltage,Current,Power" << endl;

while (!(a ==-100))
{

cout<<"Enter voltage:";
cin>>a;
cout<<"Enter current:";
cin>>b;
c=a*b;
outdata<<a<<","<<b<<","<<c<< endl;

indata.open("out.csv");


}

system("pause");
return 0;
}



Voltage Current Power
3 4 12
3 3 9
3 3 9
3 3 9
-100 3 -300
Last edited on
Line 14: a is unititialized. First time through the loop, results are unpredictable.

Line 22: You need to test for -100 before you write to the outdata file.

Line 24: This will open the file every time through the loop.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Last edited on
Also, please get into the habit of applying meaningful names to your variables. In tiny applications like this it doesn't matter so much, but it will help you in the future if you plan to ever write anything larger.

Line 8: 'd' is not being used and there is no fourth variable needed in this equation set. Total resistance can be calculated given the variables present.

AbstractionAnon (1777): ok..Now I have initialized (all a,b,c)=0 and placed indata.open("out.csv"); in the main before system("pause");..
How do I test for -100 before I write to the outdata file..I dont get you.


1
2
3
4
5
}
indata.open("out.csv");
system("pause");
return 0;
}


Computergeek01: ok noted..I hv used a,b,c n etc cz it is indeed a tiny application :)
When -100 is entered for a, you want to skip the rest of the loop. There are a couple of ways to do this:

Using a break statement:
1
2
3
4
5
6
7
8
9
10
while (a !=-100)
{  cout<<"Enter voltage:";
    cin>>a; 
    if (a == -100)
      break;  // Exit the loop
    cout<<"Enter current:";
    cin>>b;
    c=a*b;
    outdata<<a<<","<<b<<","<<c<< endl;
}


Using an if statement:
1
2
3
4
5
6
7
8
9
10
while (a !=-100)
{  cout<<"Enter voltage:";
    cin>>a; 
    if (a != -100)
    { cout<<"Enter current:";
      cin>>b;
      c=a*b;
      outdata<<a<<","<<b<<","<<c<< endl;
    }
}

Last edited on
AbstractionAnon (1834) : Thanks man..I did it ! :)

One more question,how do I copy the data into a new csv file instead of the existing one every time after I quit and restart the program ?
Last edited on
Topic archived. No new replies allowed.