c++ my counter adds an extra count - c++

I am new to programming and trying to teach myself but my counter is displaying one more than it should. it should be displaying 22, but it is displaying 23.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//Main and variable data type initializing
void main()
{ float c,l,x,y,z;
int count;
string input, output;
string finput, foutput;
fstream i,o; //i = input file; o = output file;
//Getting the name of the files
cout << "XZY Multiply Program\n" << endl;
cout << "Enter the input file name: c:/";
cin >> input;
cout << "Enter the output file name: c:/";
cin >> output;
//inserts the beginning of the file and file extension.
finput = "c:/" + input;
foutput = "c:/" + output;
//Opens files
i.open(finput.data(),ios::in);
o.open(foutput.data(),ios::out);
//Initialize count and sum of variables
count = 0;
x=0;
y=0;
z=0;
//loop through input file
while(!i.eof() && !o.eof())
{ count++;
if (i.good() && o.good())
{
i >> c;
i >> l;
o << fixed << showpoint << setprecision(4);
o << setw(7) << c;
o << setprecision(2);
o << setw(9) << l;
o << setprecision(3);
o << setw(10) << (l*c) << endl;
// Adds columns
x = x+c;
y = y+l;
z = z+(l*c);
}
else
{
cout << "no good";
}
}
i.close();
o.close();
//Display the output of the counter and Sums of columns
cout << fixed << showpoint << setprecision(2);
cout << "\n" << count << " lines in file " << endl;
cout << "X sum = " << setw(8) << right << x << endl;
cout << "Y sum = " << setw(8) << right << y << endl;
cout << "Z sum = " << setw(8) << right << z << endl;
}
7.2830 84.40
9.1327 124.02
7.2619 133.16
6.2527 43.96
4.2160 24.08
5.2724 57.80
5.2025 73.89
-9.9500 80.53
0.2790 -12.43
2.2115 3.37
3.1222 13.63
16.2413 223.01
-4.2026 33.78
-7.1914 42.89
4.1417 53.42
6.1714 61.66
9.2516 73.68
15.2419 383.66
6.2715 93.53
-3.2016 3.46
12.2013 213.63
3.1824 23.85

Using .eof() or .good() as a loop condition almost always produces buggy code, as it does in this case.
Rather, perform the input and check its result in the loop condition, like so:
while(i >> c >> l)
{ count++;
o << fixed << showpoint << setprecision(4);
o << setw(7) << c;
...
References:
Why is iostream::eof inside a loop condition considered wrong?
http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5

I assume that after reading the last number from the input file the end of file has not been seen, yet. Try adding
if (!i.good()) break;
after each input statement (>>) to prevent the loop body to be executed after a failed input.

Related

how to use if else c++

How do you provide a condition in the if statement, if the variable is an integer data type then it will be displayed, and if the variable is any other data type then something else will be displayed?
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
using namespace std;
int main() {
char pilih,pilih2;
int p, l, a, t, r,ulang = 4;
float luas1, luas2, luas3, keliling1, keliling2, keliling3, phi = 3.14;
while (ulang > 0) {
pilihUlang:
cout << "Pilih jenis bangun datar berikut :\n 1. Persegi panjang\n 2. Segitiga sama sisi\n 3. Lingkaran" << endl;
cout << "Masukan pilihan anda [1/2/3] : ";
cin >> pilih;
system("cls");
switch (pilih) {
case '1':
system("color 07");
cout << "Luas Dan Keliling Persegi Panjang" << endl;
cout << "Masukan Panjang = ";
cin >> p;
if (?) { // <-- here
cout << "Masukan Lebar = ";
cin >> l;
system("cls");
cout << "Luas dan keliling Persegi Panjang dengan panjang " << p << " dan lebar " << l << ", yaitu :" << endl;
luas1 = p * l;
keliling1 = 2 * (p + l);
cout << "Luas = " << luas1 << endl;
cout << "Keliling = " << keliling1 << endl;
cout << "Sisa bisa memilih ulang " << ulang - 1 << " kali." << endl;
break;
}
else {
//...
}
From the istream::operator>> man page:
If extraction fails (e.g. if a letter was entered where a digit is
expected), zero is written to value and failbit is set.
So, your function could test the cin.good() method to see if the >> operation was successful, like this:
cin >> p;
if (cin.good()) {
cout << "The integer you typed was " << p << endl;
} else {
cout << "Hey, that wasn't an integer!" << endl;
}

How to shift characters to ASCII values in a file based on user input c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have an assignment using a version of Ceasar cipher but it shifts characters in a file based on user input. For instance, if the user enters the shift value as 1, it would change 'a' to 'b'. I've tried typing to the out file and adding the shift value to the characters but it doesnt output anything to the out1 file and I can't figure out the right way to type this so the code does what I want it to do. Any info would help, here's my code:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cctype>
using namespace std;
double Percent(double&, double&);
int main()
{
//Declare user variables
int shift;
char ifilename[25], ofilename[25], ch;
ifstream in1;
ofstream out1;
double other = 0, letter, nums = 0;
//Attach files
do {
in1.clear(); //clear status flags
//Prompt user to enter name of input file and amount of shift
cout << "Please enter the name of the input file." << endl;
cout << "Filename: ";
cin >> ifilename;
//Open file name
in1.open(ifilename);
//Error message if no file
if (!in1)
cout << "That is not a valid file. Try again\n";
}
while (!in1);
do {
out1.clear(); //clear status flags
cout << "Please enter the name of the output file." << endl;
cout << "Filename: ";
cin >> ofilename;
out1.open(ofilename);
//Error message if no file
if (!out1)
cout << "That is not a valid file. Try again\n";
}
while (!out1);
//prompt user to enter shift
cout << "Please intput the shift amount: ";
cin >> shift;
cout << "Processing complete" << endl;
double count = 0;
int sum = 0, i = 0;
while (!in1.eof()) // while not end of input file
{
in1.get(ch); // read a character from input file using get()
out1 << ch; //print to output
count++; //count how many characters
i = ch;
if (i > 47 && i < 58) //count number of numbers
nums++;
else if ((i > 31 && i < 48) || (i > 57 && i < 65) || (i > 90 && i < 97) || (i > 122 && i < 127))
other++; // count number of other characters
else if ((i > 64 && i < 91) || (i > 96 && i < 123))
letter++; // count number of letters
// type to output file and shift characters
out1 << ch + shift;
}
//Tell user file input is complete and is now printing statistics
cout << "\nShifted input file Complete. Now printing statistics " << endl;
//Show statistics for file
cout << "\nStatistics for file: " << ifilename << endl;
cout << "------------------------------------------------";
//Show characters in file and stats before shift
cout << "\n\nTotal # of characters in file: " << count << endl;
cout << "Statistics before shift: " << endl;
cout << "\n\nCategory" << setw(30) << "How many in file" << setw(20) << "% of file" << endl;
cout << "----------------------------------------------------------------" << endl;
cout << "Letters" << setw(25) << letter << setw(20) << setprecision(4) << letter / count * 100 << " %" << endl;
cout << "Digits" << setw(26) << nums << setw(20) << setprecision(4) << nums / count * 100 << " %" << endl;
cout << "Other" << setw(27) << other << setw(20) << setprecision(4) << other / count * 100 << " %" << endl;
//Show user stats after shift
cout << "\nStatistics after shift: " << endl;
cout << "\n\nCategory" << setw(30) << "How many in file" << setw(20) << "% of file" << endl;
cout << "----------------------------------------------------------------" << endl;
cout << "Letters" << setw(25) << letter << setw(20) << setprecision(4) << Percent(letter, count) << " %" << endl;
cout << "Digits" << setw(26) << sum << setw(20) << setprecision(4) << nums / count * 100 << " %" << endl;
cout << "Other" << setw(27) << nums << setw(20) << setprecision(4) << other / count * 100 << " %" << endl;
//Close files
out1.close();
in1.close();
return 0;
}
double Percent(double&, double&)
{
double sum, letter, count;
sum = letter / count * 100;
return sum;
}
A simple implementation of the Caesar Cipher is to use a string of valid characters and the remainder operator, %.
char Encrypt_Via_Caesar_Cipher(char letter, unsigned int shift)
{
static const std::string vocabulary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const std::string::size_type position = vocabulary.find(letter);
char c = letter;
if (position != std::string::npos)
{
const std::string::size_type length = vocabulary.length();
c = vocabulary[(position + shift) % length];
}
return c;
}

C++ Program need help to debug

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct football_game
{
string visit_team;
int home_score;
int visit_score;
};
void printMenu();
int main()
{
int i, totalValues = 0;
ifstream inputFile;
string temp = "";
inputFile.open("games.txt");
if (!inputFile)
{
cout << "Error opening Input file!" << endl;
exit(101);
}
inputFile >> totalValues;
getline(inputFile, temp);
cout << " *** Football Game Scores *** " << endl << endl;
cout << " * Total Number of teams : " << totalValues << endl << endl;
football_game* records = new football_game[totalValues];
// while (!inputFile.eof())
// {// == NULL) {
for (i = 0; i < totalValues; i++)
{
getline(inputFile, records[i].visit_team);
cout << records[i].visit_team << endl;
inputFile >> records[i].home_score >> records[i].visit_score;
cout << records[i].home_score << " " << records[i].visit_score << endl;
getline(inputFile, temp);
}
//}
cout << endl;
int choice = 0;
int avg_home_Score = 0;
int avg_visit_Score = 0;
printMenu(); // prints menu
cout << "Please Enter a choice from the Menu : ";
cin >> choice;
cout << endl << endl;
while (true)
{
switch (choice)
{
case 1:
cout << " Score Table " << endl;
cout << " ***********************" << endl << endl;
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
for (int i = 0; i < totalValues; i++)
{
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|' << setw(7)
<< right << records[i].visit_score << " " << '|' << endl;
}
cout << endl << endl << endl;
break;
case 2:
{
string team_name;
cout << "Enter the Team Name : ";
cin >> team_name;
for (int i = 0; i < totalValues; i++)
{
if (records[i].visit_team == team_name)
{
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|'
<< setw(7) << right << records[i].visit_score << " " << '|'
<< endl;
}
}
cout << endl;
break;
}
case 3:
{
for (int i = 0; i < totalValues; i++)
avg_home_Score += records[i].home_score;
cout << "Average home_score: " << (avg_home_Score / totalValues) << endl << endl;
break;
}
case 4:
{
for (int i = 0; i < totalValues; i++)
avg_visit_Score += records[i].visit_score;
cout << "Average visit_score: " << (avg_visit_Score / totalValues) << endl << endl;
break;
}
default:
{
cout << "Please enter valid input !!" << endl;
break;
}
}
printMenu();
cin >> choice;
}
return 0;
}
void printMenu()
{
cout << " Menu Options " << endl;
cout << " ================ " << endl;
cout << " 1. Print Information of all Games[Table Form] " << endl;
cout << " 2. Print Information of a Specific Game " << endl;
cout << " 3. Print Average points scored by the Home Team during season" << endl;
cout << " 4. Print Average points scored against the Home Team" << endl << endl << endl;
}
Here is the input file i am using
games.txt
5
SD Mines
21 17
Northern State
10 3
BYU
10 21
Creighton
14 7
Sam Houston State
14 24
When i am using the 2nd option (Print Information of a Specific Game) from the output screen,
it ask me to enter the team name and when i enter the team-name.
For example: SD Mines it gives me an error, but when I enter the team-name with no space like: BYU it works fine for me.
cin >> team_name;
Takes the input only upto space.
You might want to use cin.getline() for taking space separated strings as input.
A small program demonstrating the same :
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Name is : , " << name << "!\n";
return 0;
}
std::cin ignores whitespaces by default.
To include spaces in your input try :
getline(cin, team_name);
This would pick up all the characters in a line until you press enter. This is available in
#include<string>
You need to flush the std::cin buffer after reading the choice:
#include <limits>
//...
cin >> choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Refer to this question for detailed explanation.
Also, if you want to read strings with spaces from the standard input, replace this:
cin >> team_name;
with this:
getline(cin, team_name);
as already mentioned in other answers. No need to flush std::cin this time, since you have already read the full line.
Finally, remove extra newlines from your games.txt:
5
SD Mines
21 17
Northern State
...

I am designing a programming that calculates the odds of profiting if you played several scratch- off lottery games

This is the code I have written so far to calculate the odds of profiting from playing lottery scratchers. I have to prompt the user for out output file name (output.txt), where a formatted table with the results will be written. So far my program will output the results, but not in an output file. I am not really sure how to do that or where that will go in my code.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// Declaring variables
int lowestAmountOfProfit;
char filename[]="scratcher.txt";
string gameName;
int CostOfTicket, NumberOfPrizes;
int PrizeValue, NumberOfTickets, TicketsNotClaimed;
double RemainingTickets;
double RemainingTicketsForProfit;
double odds;
// The program will ask the user to enter the lowest amount they would like to
// profit when playing the lottery.
cout << "Enter the lowest dollar amount that you would like to profit: "
cin >> lowestAmountOfProfit;
cout << "Enter the output file name: "
cout << "Generating report..."
//open input file
ifstream fin;
fin.open(filename);
//if input file does not exist
if (!fin)
{
// If the input file cannot be found.
cout << "Input file does not exist." << endl;
return 0;
}
//How the output displace will be formatted.
cout << left << setw(25) << "Game" << setw(10) << "Cost" << setw (10) << "Odds" << endl;
cout << "-----------------------------------------------" << endl;
// Reads the name of the game
while (getline(fin, gameName))
{
fin >> CostOfTicket; // Reads the cost of ticket
fin >> NumberOfPrizes; // Reads the number of prizes
RemainingTickets = 0;
RemainingTicketsForProfit = 0;
for (int i = 0; i < NumberOfPrizes; i++)
{
fin >> PrizeValue; // Reads the prize value
fin >> NumberOfTickets; // Reads the total number of tickets
fin >> TicketsNotClaimed; // Reads number tickets not claimed
//regardless of prize value*/
// The following line computes the running sum of the number of tickets remaining for that game.
RemainingTicketsForProfit = RemainingTicketsForProfit + TicketsNotClaimed;
// The next line with compute a sum of the number of remaining tickets where the user would profit.
if (PrizeValue > lowestAmountOfProfit)
{
RemainingTickets = RemainingTickets + TicketsNotClaimed;
}
}
// Tells program what to do if there are zero remaining tickets
if (RemainingTickets==0)
{
// Formats the output
cout << left << setw(25) << gameName << setw (2) << "$" << CostOfTicket << right << setw(15) << "Not possible" << endl;
}
else
{
// Tells the program to calculate the odds
odds = RemainingTicketsForProfit / RemainingTickets;
cout << left << setw(25) << gameName << setw (2) << "$" << CostOfTicket << right << setw(15) << "1 in " << setprecision(2) << fixed << odds << endl;
}
// Read the blank line
string blankLine;
fin >> blankLine;
}
// Close the input file
fin.close();
return 0;
}
You can output to a file by just declaring it as a ofstream and then basically using it as a cout. Like so:
ofstream outputFile;
outputFile.open("filename.txt");
cout << "Enter the first number: ";
cin >> num1;
outputFile << num1 << endl;
outputFile.close();

I am trying to use a do while loop to repeat a certain portion of my program and it refuses to execute properly

Okay so as the title said its refusing to execute the stuff right under the "do" function even though as far as i can tell all the parameters for a repeat have been fulfilled. So far what i get when i run the program is something along the lines of...
"Would you like to search another name?
Please enter Y for yes and n for no:"
looping over and over when i press y
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main()
{
vector <string> vName, vID, vClass;
string sName, sID, sClass, sSearch, cQuestion;
int iSize, iStudent;
// Display initial vector size
iSize = vName.size();
cout << "Student list starts with the size:" << iSize << endl;
// Get size of list from user
cout << "How many students would you like to add?" << endl;
cin >> iStudent;
cin.ignore();
// Get names, ids, and classes
for (int i = 0; i < iStudent; i++)
{
cout << "Student" << i + 1 << ":\n";
cout << "Please enter the student name: ";
getline(cin, sName);
vName.push_back(sName);
cout << "Enter ID number ";
getline(cin, sID);
vID.push_back(sID);
cout << "Enter class name ";
getline(cin, sClass);
vClass.push_back(sClass);
}
// Display header
cout << "The list of students has the size of: " << iStudent << endl;
cout << "The Student List" << endl;
cout << "\n";
cout << "Name:" << setw(30) << "ID:" << setw(38) << "Enrolled Class : " << endl;
cout << "--------------------------------------------------------------------------";
cout << "\n";
// for loop for displying list
for (int x = 0; x < vName.size() && vID.size() && vClass.size(); x++)
{
cout << vName[x] << "\t \t \t" << vID[x] << "\t \t \t" << vClass[x] << endl;
}
// Sorting function
cout << "\n";
cout << "The Student List after Sorting:" << endl;
cout << "\n";
sort(vName.begin(), vName.end());
for (int y = 0; y < vName.size(); y++)
{
cout << vName[y] << endl;
}
cout << "\n";
// Search function
do
{
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
} while (cQuestion == "Y" || cQuestion == "y");
cout << "Thank you for using this program!" << endl;
return 0;
}
Edit:
Posted whole program, please excuse any grammatical mistakes, I'm just trying to get the program down before i go in there and make it pretty.
The tail of your loop does this:
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
which will consume your string if you entered one, but leave the trailing newline in the input stream. Thus when you return to the top of the loop after entering Y or y, and do this:
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
the getline will extract an empty line.
How to consume the unread newline from the input stream is up to you. You will likely just end up using .ignore() as you did prior in your program. Or use getline to consume cQuestion. You have options. Pick one that works.
And as a side note, I would strongly advise you check your stream operations for success before assuming they "just worked". That is a hard, but necessary, habit to break. Something like this:
do
{
cout << "Please Enter a name to be searched:" << endl;
if (!getline(cin, sSearch))
break;
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
} while (getline(cin,cQuestion) && (cQuestion == "Y" || cQuestion == "y"));
If cQuestion is a char array then you need to use strcmp or stricmp to compare it with another string i.e. "Y" and "y" in this case. If cQuestion is a single char then you need to compare with 'Y' and 'y' (i.e. with a single quote)
Strings in C++ are not first class types therefore they do not have some of the string operation that exist for other basic types like ints and floats. You do have std::string as part of the standard C++ library which almost fulfills the void.
If you just change the type of cQuestion to std::string your code should work but if you want to stick with chars then you will need to change the quote style.