Saving multiple output in a text file in c++ - c++

Still trying to learn c++. Our prof wants us to make a program wherein the output of the temperature will be saved in a text file. The variable result is the output that i want to get save. Although the code works and saves the result, the problem is it only saves the first result. I've put a limit, for now i only want to save at least 5 results.
#include <iostream>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main()
{
double value, the_result, result;
int choice;
ofstream file;
file.open("output.txt");
do {
cout <<"\n\nChoose among the following:"
"\n1 = Celsius to Fahrenheit"
"\n2 = Celsius to Kelvin"
"\n3 = Fahrenheit to Celsius"
"\n4 = Fahrenheit to Kelvin"
"\n5 = Kelvin to Celsius"
"\n6 = Kelvin to Fahrenheit"
"\n7 = Exit"
"\n\nChoice:\n";
cin >> choice;
switch (choice){
case 1:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, '\n');
}else{
result = value*9/5+32;
cout <<"The result is ~"<< result << "\370";
}
break;
case 2:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, '\n');
}else{
result = value+273.15;
cout <<"The result is ~"<< result << "K";
}
break;
case 3:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, '\n');
}else{
the_result = value-32;
result = the_result*5/9;
cout <<"The result is ~"<< result << "\370" << "F";
}
break;
case 4:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, '\n');
}else{
the_result = value + 459.67;
result = the_result*5/9;
cout <<"The result is ~"<< result << "K";
}
break;
case 5:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, '\n');
}else{
result = value - 273.15;
cout <<"The result is ~"<< result << "\370";
}
break;
case 6:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, '\n');
}else{
result = value*9/5-459.67;
cout <<"The result is ~"<< result << "\370" << "F";
}
break;
case 7:
return EXIT_SUCCESS;
break;
}
for (double i=0; i<5; i++){
file << result<< endl;
}
file.close();
}
while (choice !=7);
}

Just to expand on AProgrammer's comment - The problem is after the first iteration you are trying to write to a file that you have already closed and not reopened. So as suggested you should move the file.close() outside of the do while loop

Related

how to make cin only accept a single character and int accept only numbers?

How can I make cin accept only a single letter in char datatypes and numbers only in double/int datatypes.
#include <iostream>
using namespace std;
int main (){
char opt;
int num1, num2, sum;
cout << "A. Addition" << endl << "B. Subtraction" << endl;
cout << "Enter option: "; cin >> opt;
//if I put "ab" here, I want to make cin only read the first letter if possible.
switch(opt){
case 'A': case 'a':{
cout << "Enter first number: "; cin >> num1; //accept numbers only
cout << "Enter second number: "; cin >> num2;//accept numbers only
sum = num1+num2;
cout << "The sum is " << sum;
break;
}
}
}
By definition, operator>> reading into a char will read in exactly 1 character, leaving any remaining input in the buffer for subsequent reading. You have to validate the read is successful and the character is what you are expecting before using it.
And likewise, operator>> reading into an int will read in only numbers. You have to validate the read is successful before using the number, and discard any unused input if the read fails to return a valid number.
Try something like this:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
char ReadChar(const char* prompt) {
string s;
do {
cout << prompt << ": ";
if (!(cin >> s)) throw ...;
if (s.length() == 1) break;
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Enter a single character" << endl;
}
while (true);
return s[0];
}
char ReadInt(const char* prompt) {
int value;
do {
cout << prompt << ": ";
if (cin >> value) break;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Enter a valid number" << endl;
}
while (true);
return value;
}
int main() {
char opt;
int num1, num2, result;
cout << "A. Addition" << endl << "B. Subtraction" << endl;
opt = ReadChar("Enter option");
switch (opt) {
case 'A': case 'a': {
num1 = ReadInt("Enter first number");
num2 = ReadInt("Enter second number");
result = num1 + num2;
cout << "The sum is " << result << endl;
break;
}
case 'B': case 'b': {
num1 = ReadInt("Enter first number");
num2 = ReadInt("Enter second number");
result = num1 - num2;
cout << "The difference is " << result << endl;
break;
}
default: {
cout << "Invalid option" << endl;
break;
}
}
}

Undeclared identifier- C++

I am doing a project for school and keep running into this reoccurring problem, my code does not seem to run as I have "undeclared identifiers." I have tried renaming them or redefining them but the same errors keep going or more. I am using VS code at the moment and read about maybe it was VScode itself but I get the same errors regardless.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
using namespace std;
class bankAccount {
public:
int accountNum;
string accountName;
string accountType;
double accountBalance;
double accountInterest;
double getInterest;
double updateBalance;
bankAccount(){
accountNum = 0;
accountName = "";
accountType = "";
accountBalance = 0.0;
accountInterest = 0.0;
}
void deposit()
{
long amount;
cout << "\n Please enter the amount you would like to deposit: ";
cin >> amount;
accountBalance = accountBalance + amount;
}
void withdraw()
{
long amount;
cout << "Please enter the amount you would like to withdraw: ";
cin >> amount;
if (amount <= accountBalance)
{
accountBalance = accountBalance - amount;
}
else
{
cout << "You do not have sufficient funds" << endl;
}
}
void interest(){
double getInterest;
cout << "Please enter desired interest amount: ";
cin >> getInterest;
}
void update(){
double updateBalance;
updateBalance = accountBalance * getInterest;
accountBalance += updateBalance;
}
void print(){
string print;
cout << "Welcome Back " << accountName << "," << endl;
cout << "\n Account Number: " << accountNum << endl;
cout << "\n Account Type: " << accountType << endl;
cout << "\n Current Balance: " << accountBalance << endl;
cout << "\n Account Interest: " << accountInterest << endl;
}
void openAccount(){
cout << "Enter Account Number: ";
cin >> accountNum;
cout << "Enter Account Holders Name: ";
cin >> accountName;
cout << "Enter Account Type: ";
cin >> accountType;
cout << "Enter Initial Balance: ";
cin >> accountBalance;
cout << "Enter Interest Rate: ";
cin >> accountInterest;
}
};
int main() {
int choice;
do
{
cout << "Please select the following options ";
cout << "\n 1:View Account";
cout << "\n 2: Open Account";
cout << "\n 3: Deposit" ;
cout << "\n 4: Withdraw ";
cout << "\n 5: Update account";
cin >> choice;
switch (choice)
{
case '1':
print ();
break;
case '2':
openAccount();
break;
case '3':
deposit();
break;
case '4':
withdraw();
break;
case '5':
updateBalance();
break;
}
} while (case !=5);
}
suggested creating an instance of class bankAccount somewhere before switch statement and call the functions like, instance_of_bankAccount.functionName();
At end of loop instead of (case !=5) it should be (choice != 5)
The problem with your code is that you do not have any instance of the class bankAccount, which means you try to call the function which actually does not exist. To fix it, you should create an object of the bankAccount type before the loop in which you can select the operation you want to perform:
int main() {
int choice;
bankAccount bankAcc; // this creates the object we need
do ...
And then for every case you wanted to call the function f(), add prefix bankAcc., so it becomes bankAcc.f(). In your code, it would be:
switch (choice) {
case '1':
bankAcc.print();
break;
case '2':
bankAcc.openAccount();
break;
case '3':
bankAcc.deposit();
break;
case '4':
bankAcc.withdraw();
break;
case '5':
bankAcc.updateBalance();
break;
}
Thanks to it, all functions called will know that they belong to bankAcc and they will change properties only of this particular object.
There is also another mistake in your code: did you really mean to use chars in your switch? At the moment cin >> choice reads an int, saves it in choice and then in switch it gets compared with all values corresponding to cases. The problem is that 1 is very different from '1' (which is casted to the value 49), so inputted int will never satisfy conditions from the menu you print.
Also, while (case !=5) should be changed to while (choice != 5).

reuse char array and cin.getline

I cant use the s1[40] for the second time or longer in the circle and it's always full,
and cin.getline(s1,40)
is ignored at later times
char s1[40], ans = 'y';
while (ans == 'y')
{
system("cls");
cout << "\n Enter a sentence : ";
cin.getline(s1, 40);
fflush(stdin);
cout << "\n________________________________________\n\n Again?(y/n)";
cin >> ans;
fflush(stdin);
};
cin >> ans; will actually not remove eol so next getline will read an empty line and cin >> ans; will read first symbol of line. You should make ans an array as well use getline twice:
for(;;)
{
char s1[40]{};
system("cls");
cout << "\n Enter a sentence : ";
cin.getline(s1, 40);
fflush(stdin);
if(cin.fail() or cin.bad())
{
cout << "fail" << endl;
break;
}
cout << "\n________________________________________\n\n Again?(y/n)";
char ans[2]{};
cin.getline(ans, 2);
fflush(stdin);
if(cin.fail() or cin.bad())
{
cout << "fail" << endl;
break;
}
if(0 != strcmp("y", ans))
{
break;
}
}

cin.getline() isn't working with switch statement

I've been trying to work on a program for class but for some reason when i input the number one for the program it goes to case 1 but then it doesn't let me enter a string and goes straight back to the menu. Ex) enter in 1 the result is: Enter a string: 01. Adds number but ignores anything that not a number.
If I use a regular cin statement the code will execute perfectly fine. I don't understand why it is doing this. Can somebody help?
#include <iostream>
#include <cctype>
using namespace std;
void firstChoice(char []);
int main()
{
int choice;
int answer;
const int SIZE = 100;
char line[SIZE];
do
{
cout << "1. Adds numbers but ignores anything thats not a number." << endl;
cout << "2. Count the number of consonants in a string." << endl;
cout << "3. Counts the vowels in a string." << endl;
cout << "4. Counts whitespace characters in a string." << endl;
cout << "Enter a number to access that program or 0 to end it: ";
cin >> choice;
switch(choice)
{
case 1:
cout << "\nEnter a string: ";
cin.getline(line, SIZE);
firstChoice(line);
break;
case 2:
cout << "Enter a string: ";
cin.getline(line, SIZE);
break;
case 3:
cout << "Enter a string: ";
cin.getline(line, SIZE);
break;
case 4:
cout << "Enter a string: ";
cin.getline(line, SIZE);
break;
}
}
while(choice != 0);
return 0;
}
void firstChoice(char line[])
{
int size2 = 0;
int sum = 0;
while(line[size2] != '\0')
{
if(isalpha(line[size2]))
{
line[size2] = 0;
}
sum += line[size2];
size2++;
}
cout << sum;
}
After this statement
cin >> choice;
use
#include <limits>
//...
cin >> choice;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

Having to input value twice to work C++

#include <iostream>
#include <limits>
#include <math.h>
using namespace std;
int main()
{
float startTemperature;
float endTemperature;
float loopTemperature;
float stepSize;
float i;
float numberOne;
cout << "Please enter a start temperature: " << endl;;
cin >> startTemperature;
while(!(cin >> startTemperature)){
cin.clear();
cout << "Invalid input. Try again: ";
}
cout << "Please enter an end temperature: ";
cin >> endTemperature;
while(!(cin >> endTemperature)) {
cin.clear();
cin.ignore(256, '\n');
cout << "Invalid temperature. Please try again: ";
}
cout << "Please enter a step size: ";
cin >> stepSize;
while(!(cin >> stepSize)) {
cin.clear();
cin.ignore(256, '\n');
}
for(i = startTemperature; i < endTemperature; i += stepSize) {
if(i == startTemperature) {
cout << "Celsius" << endl;
cout << "-------" << endl;
cout << startTemperature << endl;
loopTemperature = startTemperature + stepSize;
}
loopTemperature += stepSize;
if(loopTemperature > 20) {
break;
}
cout << loopTemperature << endl;
}
}
Hi, The problem with this code is that I have to input the value of the temperature twice. I have looked at other answers and I think it is something to do with the cin buffer but I don't know exactly what is wrong.
In the line
cin >> startTemperature; // <---problem here
while(!(cin >> startTemperature)){
cin.clear();
cout << "Invalid input. Try again: ";
}
You are taking input once, then again in the loop. That's is why you had to give input twice.
Just remove first input line, same for endTemparature and stepSize.
You're asking for input before the while loop, then again in the loop condition statement. Change the condition in your while statement to
while(!cin){
//error handling you already have
cin>>startTemperature; //endTemperature respectively
}
It's not only for the temperature but rather for every input. Change your code to the one below:
cout << "Please enter a start temperature: " << endl;;
while (!(cin >> startTemperature)){
cin.clear();
cin.ignore(std::numeric_limits<int>::max(), '\n');
cout << "Invalid input. Try again: ";
}
cout << "Please enter an end temperature: ";
while (!(cin >> endTemperature)) {
cin.clear();
cin.ignore(std::numeric_limits<int>::max(), '\n');
cout << "Invalid temperature. Please try again: ";
}
cout << "Please enter a step size: ";
while (!(cin >> stepSize)) {
cin.clear();
cin.ignore(std::numeric_limits<int>::max(), '\n');
cout << "Invalid step size. Please try again: ";
}
Reason:
You had redundant cin calls. Also use std::cin.ignore(std::numeric_limits<int>::max(), '\n'); instead of arbitrary number 256.