C++ trouble with outputing sum/avg - visual-c++

am taking a class of C++ and been asked to write a program that reads integers from a file.
first request is to output all of the integers in one line
and the second request is to output the average of the integers
ive tried what has been written in the book, and when I try to cout the sum or the average, it output the addition number by number not just the total
how can I fix this? i want the simplest code possible, I dont want anything that we didnt take in class yet
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
ifstream infile;
ofstream outfile;
int main()
{
int num;
ifstream infile;
ofstream outfile;
outfile.open("Answer.txt");
infile.open("DataFile2.txt");
infile >> num;
while (infile)
{
outfile << num << " ";
infile >> num;
}
infile.close();
infile.open("DataFile2.txt");
int sum = 0;
while (infile)
{
double avg;
infile >> num;
sum = sum + num;
avg = sum / 14;
cout << endl << sum << avg;
}
}

There are a lot of mistakes in your code.You should declare the avg variable outside the while loop.Also, you should calculate the average and print it after the while loop has finished looping.Also you are dividing the sum by 14 (constant) which is not good, since you don't know how many integers are in the file.
The code should look something like this:
int sum = 0;
double avg;
while (infile) {
infile >> num;
sum = sum + num;
}
avg = sum / 14;
cout << endl << sum << avg;

Related

c++ program replace digits in a given number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How would you be able to replace digits in a given number using basic c++. Example if the number is 23444 and you want to take the old digit 4 and replace is with a new digit 5 to get a new number 23555.
I have some work done below but when I enter the inputs, it ends up giving me an incorrect result.
cout << "Enter the number: " << endl;
cin >> number;
cout << "Enter the old digit: " << endl;
cin >> oldDigit;
cout << "Enter the newDigit: " << endl;
cin >> newDigit;
newDigit=oldDigit;
cout << Newnum << endl;
You can convert int to char* using itoa() and iterate over it to
check does it contain number. If it does, get 4's position and replace
it with 5.
I know you didnt work with strings, but it can be helpful in your case.
Simple code:
#include <string.h>
#include <iostream>
#include <stdlib.h>
int main(){
int numer;
std::cin>>numer;
char* str;
itoa(numer, str, 10);
for(int i = 0; i < strlen(str); i++){
if(str[i] == '4') str[i]='5';
}
}
If I understand you correctly, you don't just want to simply add 111, you want to treat the number as a string, then change elements in the array. Is that correct?
This may get you on the right track:
Convert an int to ASCII character
if you really want to use only int to do this, here is a working example (base on some of your code)
#include <iostream>
using namespace std;
int replaceDig( int num, int oldDigit, int newDigit)
{
if(num==0)return 0;
int digit = num%10;
if(digit==oldDigit)digit = newDigit;
return replaceDig(num/10,oldDigit,newDigit)*10+digit;
}
int main()
{
int num, newnum, oldDigit, newDigit;
cout << "Enter the number: " << endl;
cin >> num;
cout << "Enter the old digit: " << endl;
cin >> oldDigit;
cout << "Enter the newDigit: " << endl;
cin >> newDigit;
newnum = replaceDig(num, oldDigit, newDigit);
cout << newnum << endl;
return newnum; //do you really want to return this?
}
I have come up with a solution . Don't know if it contains bug or not. Please let me know.
int num = 23444 ,new_num = 0;
int mod;
int exponent = 0;
/**
* Now form the new number
*/
while ( num > 0 ) {
mod = num % 10;
num /= 10;
if ( mod == 4 ) // check whether this is the old digit or not
new_num += 5 * pow( 10 , exp); // replace with new digit
else
new_num += mod * pow(10 , exp); // otherwise no change
exp++;
}
num = new_num;
std::cout << num;
I hope this works for you -
std::string s = std::to_string(23444);
std::replace( s.begin(), s.end(), '4', '5');
int num = std::stoi(s);
int replaceDig( int num, int oldDigit, int newDigit) // replacing the old digits in a number with a new digit
{
int position = numDigits(num);
int remainder = num;
int currentDigit;
while (remainder >0)
{
currentDigit=(num/pow(10,position))%10;
if(currentDigit==oldDigit)
{
num = num - oldDigit*pow(10,position);
num = num + newDigit*pow(10,position);
}
remainder = remainder/10;
position--;
}
}
This is the general idea, I guess. I didn't try to compile it though. And of course, this version isn't really optimized and we could find some more efficient ways of doing it. Oh, and it doesn't work with negative numbers, but this should be quite easy to adapt.

cin unintentionally skipping user input

I am trying to write a loop that validates user input, and then repeats if the input is bad. The input must be either a binary number (as a string) or a decimal number (as an int). I have seperate functions to validate this input, but they are not causing any trouble.
The problem arises when I select 1 or 2, and then willingly enter an invalid binary or decimal number. At this point, the do-while loop repeats successfully. The program prints another request for user input to cout, But when it comes time for the user to enter input, the program thinks that there is input in the console before I even enter anything. I believe this is a problem with whitespace/control characters in the buffer, but I am not sure how to fix it. I have tried using std::cin >> std::ws to clear any straggling white space, but no luck.
#include <iostream>
#include <string>
#include <limits>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
using std::cout;
using std::cin;
using std::endl;
using std::numeric_limits;
using std::max;
using std::streamsize;
using std::string;
//int toDecimal;
//true is is binary
bool validateBinary(const string &binaryNumber){
for(int i = 0; i < binaryNumber.length(); i++){
if((binaryNumber[i] != 1) && (binaryNumber[i] != 0)){
return false;
}
}
return true;
}
//true if is decimal
bool validateDecimal(){
return cin;
}
int main() {
int conversionType = 0; //we initialize conversionType to a default value of 0 to ensure the copiler it will always have a value
bool isBinary = false;
bool isDecimal = false;
string binaryNumberInput;
int decimalNumberInput;
do {
if(conversionType == 0){
cout << "Enter 1 to convert binary to decimal," << endl;
cout << "2 to convert decimal to binary, " << endl;
cout << "or 3 to exit the program: ";
std::cin >> std::ws; //to clear any whitespace fron cin
cin >> conversionType; //upon a second iteration, this value is read in before a user input is given
}
if(!cin || (conversionType != 1 && conversionType != 2)){
cout << "Incorrect input." << endl;
cin.clear(); //clear the fail bit
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //used to ignore not-numeric input
}
cout << "You have selected option " << conversionType << "." << endl;
if(conversionType == 1){
cout << "Please enter a binary number: ";
cin >> binaryNumberInput;
isBinary = validateBinary(binaryNumberInput);
if(!isBinary){
cout << "The numbered you entered is not a binary number!" << endl;
conversionType = 0;
}
}
if(conversionType == 2){
cout << "Please enter a decimal number: ";
cin >> decimalNumberInput;
isDecimal = validateDecimal(); //true if succeeded, meaning is a number
if(!isDecimal){
cout << "The numbered you entered is not a decimal number!" << endl;
conversionType = 0;
}
}
}
while((conversionType != 1 && conversionType != 2) || (isBinary == isDecimal));
return 0;
}
Rather than debug your current program you might want to consider using the standard library to simply things
#include <iostream>
#include <string>
#include <bitset>
#include <climits>
#include <limits>
template<typename T>
void get(T& value)
{
while (!(std::cin >> value)) {
std::cout << "Invalid input\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
int main()
{
std::cout << "Enter 1 to convert binary to decimal,\n" <<
"2 to convert decimal to binary\n";
int option;
if (std::cin >> option) {
switch (option) {
case 1: {
std::bitset<CHAR_BIT * sizeof(unsigned long long)> bits;
get(bits);
std::cout << bits.to_ullong() << '\n';
break;
}
case 2: {
unsigned long long i;
get(i);
std::cout << std::bitset<CHAR_BIT * sizeof i>(i) << '\n';
break;
}
}
}
}
If you want this to loop you should be able to add it back in again easily enough.

Standard Deviation Code Output Error

I can't see my output from this code I have written. I'm trying to calculate the mean and standard deviation of a set of numbers from a file. I'm lost as to what the problem is and I won't know if my code is right until I can see output. Here's what I have so far:
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
int main()
{
// Declare Variables
int n;
int xi;
int sdv;
int sum;
int sum2;
int sum3;
int mean;
// Declare and open input files
ifstream inData;
inData.open("score.dat");
if (!inData) // Incorrect Files
{
cout << "Cannot open input file." << endl;
return 1;
}
// Initialize variables and output
inData >> xi;
n = 0;
sum = 0;
sum3 = 0;
sdv = 0;
mean = 0;
while (inData)
{
sum += xi;
sum2 = sum * sum;
sum3 += (xi * xi);
mean = sum / n;
sdv = (sum3 - sum2) / (n * (n - 1));
inData >> xi;
}
// Print commands
cout << "The Standard Deviation of the Tests is:" << sdv << endl;
cout << "The Mean of the Tests is: " << mean << endl;
inData.close();
system("pause");
return 0;
}
After running your code I found a few bugs. You probably don't get any output because the program crashes the first time through the while loop on the line:
mean = sum / n;
due to a divide by zero error.
The other bug is that you don't increase (increment) the value of n in your loop, so you always only have one number.
Adding an n++ at the beginning of your loop will fix that
while (inData)
{
n++;
sum += xi;
...
But you still get a divide by zero on the sdv when n == 1:
sdv = (sum3 - sum2) / (1 * (1 - 1));
if you add a condition before the division it will work:
if (n >= 2)
sdv = (sum3 - sum2) / (n * (n - 1));
Look into debugging tools like gdb to help catch things like this.

Putting values from one Array into another

I'm at a loss here, so I am looking for any hints to point me in the right direction. I can't figure out how to input the Celsius values that I converted from the Fahrenheit temperatures into the centigrade array. I tried to work in another for loop for that very purpose but it only outputs the last value for C after the calculation from the first for loop. Any ideas? Thanks in advance.
// Temperature Converter
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::setw;
int main()
double temps[] = { 65.5, 68.0, 38.1, 75.0, 77.5, 76.4, 73.8, 80.1, 55.1, 32.3, 91.2, 55.0 };
double centigrade[] = { 0 }, C(0);
int i(0);
cout << setw(13) << "Farenheit " << setw(9) << " Centigrade";
cout << endl;
for (double t : temps)
{
C = (t - 32) * 5 / 9;
cout << setw(10) << t << setw(12) << C;
cout << endl;
}
for (i = 0; i <= 12; i++)
{
centigrade[i] = C;
cout << centigrade[i] << endl;
}
return 0;
}
Here is a full working example based on the other answer.
#include <iostream>
using std::cout;
using std::endl;
int main() {
double temps[] = { 65.5, 68.0, 38.1, 75.0, 77.5, 76.4, 73.8, 80.1, 55.1, 32.3, 91.2, 55.0 };
const int count = sizeof(temps) / sizeof(temps[0]);
double centigrade[count];
for (int i = 0; i < count; i++) {
centigrade[i] = (temps[i] - 32) * 5 / 9;
cout << centigrade[i] << endl;
}
return 0;
}
If you want to work without an explicit indexing loop, then replace double centigrade[count]; with std::vector<double> centigrade, and replace the loop with:
for (double t : temps)
centigrade.push_back((t - 32) * 5 / 9);
If you then wanted an array back for some reason, you could use this trick to get an array back:
double* array_version = &centigrade[0];
Store values in the array in the first loop itself..
for (i=0;i<=12;i++)
{
centigrade[i]= (temps[i] - 32) * 5 / 9;
cout << setw(10) << temps[i] << setw(12) << centigrade[i];
cout << endl;
}
U can generalize the for loop by finding the size of temps array dynamically..maybe
sizeof (temps) / sizeof (temps[0]);
Also allocate memory for centigrade array accordingly.
I am adding a new answer based on clarifications to the OP's question, rather than updating my existing answer, because I feel the context is more clear this way.
If you want to use a range-based loop, and avoid std::vector, there is a way to do it, but this solution is more in the spirit of C thanC++, because it uses pointer arithmetic.
#include <iostream>
using std::cout;
using std::endl;
int main() {
double temps[] = { 65.5, 68.0, 38.1, 75.0, 77.5, 76.4, 73.8, 80.1, 55.1, 32.3, 91.2, 55.0 };
const int count = sizeof(temps) / sizeof(temps[0]);
double centigrade[count];
double * walker = centigrade;
for (double t : temps)
*walker++ = (t - 32) * 5 / 9;
// verify results by printing.
for (double t: centigrade)
cout << t << endl;
return 0;
}

Why doesn't unsigned char* work with ifstream::read?

I am a beginner with C++. I have a new project at work where I have to learn it, so I'm trying some things just to test my understanding. For this problem, I'm trying to read a file and then print it on screen. Super simple, just trying to get good at it and understand the functions that I'm using. I copied some text from a MS Word document into a notepad (*.txt) file, and I'm trying to read this *.txt file. All of the text in the word document is bolded, but other than that there are no 'unusual' characters. Everything prints out on the screen as it appears in the document except the bolded " - " symbol. This character is printed as the "u" with a hat character ("so called extended ASCII" code 150). I try to print out the integer value of this character in my array (which should be 150) but I get -106. I realize this signed integer has the same bits as the unsigned integer 150. My question is how to get the output to say 150? Here's my code:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
unsigned char* input1;
int input1size = 57;
ifstream file("hello_world2.txt",ios::binary | ios::ate);
if (file.is_open()){
int size;
size = (int) file.tellg();
cout <<"This file is " << size << " bytes." << endl;
file.seekg(0,ios::beg);
input1 = new unsigned char[input1size];
file.read(input1, input1size);
cout << "The first " << input1size <<" characters of this file are:" << endl<<endl;
for (int i=0; i<input1size; i++) {
cout << input1[i];
}
cout<<endl;
}
else {
cout <<"Unable to open file" << endl;
int paus;
cin>>paus;
return 0;
}
file.close();
int charcheck = 25;
int a=0;
int a1=0;
int a2=0;
unsigned int a3=0;
unsigned short int a4=0;
short int a5=0;
a = input1[charcheck];
a1 = input1[charcheck-1];
a2 = input1[charcheck+1];
a3 = input1[charcheck];
a4 = input1[charcheck];
a5 = input1[charcheck];
cout <<endl<<"ASCII code for char in input1[" << charcheck-1 <<"] is: " << a1 << endl;
cout <<endl<<"ASCII code for char in input1[" << charcheck <<"] is: " << a << endl;
cout <<endl<<"ASCII code for char in input1[" << charcheck+1 <<"] is: " << a2 << endl;
cout <<endl<<"ASCII code for char in input1[" << charcheck <<"] as unsigned int: " << a3 << endl;
cout <<endl<<"ASCII code for char in input1[" << charcheck <<"] as unsigned short int: " << a4 << endl;
cout <<endl<<"ASCII code for char in input1[" << charcheck <<"] as short int: " << a5 << endl;
int paus;
cin>>paus;
return 0;
}
Output for all this looks like:
This file is 80 bytes.
The first 57 characters of this file are:
STATUS REPORT
PERIOD 01 u 31 JUL 09
TASK 310: APPLIC
ASCII code for char in input1[24] is: 32
ASCII code for char in input1[25] is: -106
ASCII code for char in input1[26] is: 32
ASCII code for char in input1[25] as unsigned int: 4294967190
ASCII code for char in input1[25] as unsigned short int: 65430
ASCII code for char in input1[25] as short int: -106
So it appears "int a" is always read as signed. When I try to make "a" unsigned, it turns all the bits left of the eight bits for the char to 1's. Why is this? Sorry for the length of the question, just trying to be detailed. Thanks!
What you're dealing with is the sign-extension that takes place when the char is promoted to int when you assign it to one of your a? variables.
All the higher order bits must be set to 1 to keep it the same negative value as was in the smaller storage of the char.

Resources