I am trying to get numbers into a string in a loop but convert them immediately and convert it to a double so the 3 numbers can be added and used to get an average. This is my code:
string name;
double num = 0, many = 0, total = 0, value = 0;
inputFile.open("Rainfall.txt");
for (int count = 1; count <= 6; count++)
{
inputFile >> name;
if (count == 1 || count == 3 || count == 5)
{
continue;
}
num = stod(name);
num += total;
}
cout << total << endl;
While this gives me a simple one line output of 0 i now need to convert the string to a double. The input file looks like:
january 1.2
feruary 2.3
march 2.4
August 2.3 September 2.4
Here is a slightly better way assuming your input file structure stays intact (does not sanitize inputs) and std::stod will fail badly on input that cannot be converted to double. You can simply read your given month and monthly rainfall total into their appropriate variable type at the same time. If you put the whole thing in a while loop, it will keep reading your input until it either reaches the end of the file or the stream has an error.
#include <iostream>
#include <fstream>
int main()
{
double total(0.0);
std::ifstream inputFile("Rainfall.txt");
if (inputFile.is_open())
{
std::string month;
double rain(0.0);
while(inputFile >> month >> rain)
{
total += rain;
}
inputFile.close(); ///< technically not necessary
}
std::cout << "total rainfall " << total << std::endl;
return 0;
}
Related
I am a beginner in c++ coding and i have an assignment for my class. I am trying to read the first line of integers separated by spaces 2 spaces in the file (cannot use arrays or vectors). I have seen many tutorials telling me to use getline () and simply reading each and every integer and storing it into its own variable, but neither method has been working for me. Does anybody have a way to read in the first line with a while loop and have it so that I can then find the maximum and minimum values from the line, as well as calculate the average EXCLUDING the maximum and minimum values?
sample input i was instructed to analyze is as follows
5 7 9 8 7
30032
51111
52000
42000
9 8 6 3 7
70000
23765
24000
41004
Here is what I have so far.
{
void PrintIntro (); {
cout << "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-" <<endl;
cout << "Welcome to Tallahassee Idol! Where Stars are Born!!!" <<endl;
cout << "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-" <<endl<<endl;
}
/*******************************************************************************/
void OpenFile (); {
ifstream myFile; // filestream for input file
string fileName; // string for user to input filename
cout <<"Enter a valid filename (no blanks please): ";
cin >> fileName;
myFile.open(fileName);
while (!myFile) {
cout << "Please re-enter a valid filename: "<<endl<<endl;
cin >> fileName;
myFile.open(fileName);
}
}
/*******************************************************************************/
void GetJudgeScore1 (); {
ifstream myFile; // filestream for input file
string fileName; // string for user to input filename
int player1Total = 0; // total score for player 1
int player1Average = 0; // average for player 1
int highScore1 = 0; // highest score to be excluded
int lowScore1 = 100; // lowest score to be excluded
const int judgeAmt = 5;
cout << "Processing Judge Data for Contestant 1" <<endl;
cout << "=====================================" <<endl;
cout << "Judge scores are: ";
if (myFile.is_open()){ // if the file is open, read data in
// here is where i ran into problems
}
}
return 0;
}
You can use a combination of std::string and std::istringstream and std::getline to iterate through the different integers in the line as shown below. The explanation is given in the comments.
#include <iostream>
#include<string>
#include <sstream>
#include <fstream>
#include <climits>
int main()
{
std::string line;//for storing a single line
int max = INT_MIN, min = INT_MAX, num = 0, count =0;
std::ifstream inFile("input.txt");
if(inFile)
{
while(std::getline(inFile, line))//go line by line
{
std::istringstream ss(line);
while(ss >> num)//go number by number
{
if(num > max)
{
max = num;//update the maximum
}
if(num < min)
{
min = num; //update the minimum
}
++count;
}
//you can add an if statement here to print the result only if count > 1
std::cout<<"max is: "<<max<<std::endl;
std::cout<<"min is: "<<min<<std::endl;
count = 0; //make the count 0 for next iteration
max = INT_MIN; //reset max
min = INT_MAX; //reset min
std::cout<<"----------------------"<<std::endl;
}
}
else
{
std::cout<<"input file cannot be opened"<<std::endl;
}
return 0;
}
The output of the above program can be seen here:
max is: 9
min is: 5
----------------------
max is: 30032
min is: 30032
----------------------
max is: 51111
min is: 51111
----------------------
max is: 52000
min is: 52000
----------------------
max is: 42000
min is: 42000
----------------------
max is: 9
min is: 3
----------------------
max is: 70000
min is: 70000
----------------------
max is: 23765
min is: 23765
----------------------
max is: 24000
min is: 24000
----------------------
max is: 41004
min is: 41004
----------------------
Method 2
By looking at your comments below, it seems you do not want(or not allowed) to use climits. The below program shows how you can find the max and min without using climits.
#include <iostream>
#include<string>
#include <sstream>
#include <fstream>
int main()
{
std::string line;//for storing a single line
std::string numWord; //for storing a single number as std::string
int max = 0, min = 0, num = 0, count =0;
std::ifstream inFile("input.txt");
if(inFile)
{
while(std::getline(inFile, line))//go line by line
{
std::istringstream ss(line);
//read the first number in max and min
ss >> max;
min = max;
while(ss >> num)//go number by number
{
if(num > max)
{
max = num;//update the maximum
}
if(num < min)
{
min = num; //update the minimum
}
++count;
}
//you can add an if statement here to print the result only if count > 1
std::cout<<"max is: "<<max<<std::endl;
std::cout<<"min is: "<<min<<std::endl;
count = 0; //make the count 0 for next iteration
max = 0; //reset max
min = 0; //reset min
std::cout<<"----------------------"<<std::endl;
}
}
else
{
std::cout<<"input file cannot be opened"<<std::endl;
}
return 0;
}
The output of the above program can be seen here.
Note
Since this is a homework problem, i am skipping finding out the average of the numbers so that you can modify the above program accordingly and so that i don't give the whole solution myself. Note that since your requirement is that not to use std::vector or arrays, i haven't used them in my program.
Hint:(for finding average) Add a variable called sum or average and add value of variable num to it inside the while loop.
I am unsure as to what you mean by "cannot use arrays or vectors." The following code will read each line and save it to a string, convert it, and add it to an integer array, for easier storage. You could use multiple variables instead.
#include <fstream>
#include <string>
void getData() {
std::string output;
int i = 0, data[10]; // Pre-defined array size, looking at your data set.
std::ifstream myFile;
myFile.open("Path\\To\\Your\\File.txt", ios::in);
while(getline(myFile, output))
{
data[i] = std::stoi(output);
i++;
std::cout << data[i] << "\n";
}
myFile.close();
}
Output:
57987
30032
51111
52000
42000
98637
70000
23765
24000
41004
How can I have an output of
Sample Input No.1:
9
Sample Output No.1:
1.2.3.4.5.6.7.8.9
If you input numbers less than or equal to 9, the output should be (1.2.3.4.5.6.7.8.9)
And if you input numbers greater than 9, for example:
Sample Input No.2:
20
Sample Output No.2:
01.02.03.04.05.06.07.08.09.10
11.12.13.14.15.16.17.18.19.20
My code below is for Sample Input & Output No.2. I tried adding another for loop for SAMPLE NO.1 but it still reads Sample No.2 code. What should I do?
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int a, num;
cin >> num;
if (num > 100 || num <= 1){
cout << "OUT OF RANGE";
}
else {
for (int a = 1; a < num; a++){
cout << setfill('0') << setw(2) << a << ".";
}
cout << num;
}
}
kind of new to programming, don't know much🥲
As a possible solution, you could read the input as a string, then convert it to an integer.
Use the string length as the field width for the setw manipulator.
This should be able to handle values of (theoretically) arbitrary length.
I am new to C++, trying to import dates into a program, adding up digits of day, month, year resp and writing back to txt.
input data
sl.no name day month year
1 Rob 15 05 2019
2 Tim 12 06 2002
Desired output data in txt
sl.no name day month year
1 Rob 6 5 3
2 Tim 3 6 4
I have been able to import data from a txt file and also add the digits in day but it does not repeat forward. what am i doing wrong ?
sample code
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream theFile("data.txt");
int id,day,month,year,daysum=0,monthsum=0, yearsum=0;
string name;
while (theFile >> id >> name >> day >> month >> year)
{
cout << id << ", "<< name <<", "<< day<<", "<<month <<", "<< year<<","<< endl;
}
while (day > 0)
{
daysum = daysum + (day % 10);
day = day / 10;
cout << daysum << endl;
}
I am no expert . but have been in your spot a few months ago.. break down the problem into smaller steps..
My approach..
Pseudo Code:
Ditch the header
Create a function for adding the digits
Read data from file
Use a loop to run through each element of the every column and use the function created
Store results in a variable
Output variable to a new text file
comment if there is a specific area where you are stuck..
Try this to reduce it to single digits.. knit to other parts of your code..
#include <iostream>
using namespace std;
int main()
{
long long num;
cout << "Enter a number: ";
cin >> num;
int sum = 0;
while (1)
{
sum += (num % 10);
num /= 10;
if (0 == num)
{
if (sum > 9)
{
num = sum;
sum = 0;
}
else
{
cout << "Answer: ";
cout << sum << endl;
return 0;
}
}
};
return 0;
}
you are reading the file and data wrong,
you need to discard the header (sl.no name day month year)
and then accumulate the daysum while reading the file progressively one row after the other until the end...
Im trying to calculate the average out of a couple of number inside an char array. The reason for this is that i imported data from a text document and i made it read only every 2nd line to get the numbers that i wanted.
Now i need to get the average out of these numbers but i cant make it work. I'm starting to get mad about this and i feel that the solution would be rather simple.
EDIT:
The file consists of names and numbers. I.e:
Jason Smith
32
Mary Jane
52
Stevie Wonder
68
Micheal Jackson
59
#include <fstream>
#include <iostream>
using namespace std;
double averageNum(char array[], int size) { // A function to calculate the average number
int sum = 0;
double avg;
for(int i=0; i<size; i++){
array[i]+= sum;
}
avg = sum / size;
return avg;
}
int main(){
char age [50][30];
double avg;
int rows = 0;
ifstream elevInfo("elevinfo.txt"); // Opens a stream to get data from the document
if (! elevInfo){ // Error message if the file couldn't be found
cout << "Could not find the file elevinfo.txt" << endl;
return (1);
}
while(elevInfo.getline(age[rows/2], 30)){ // Reading every 2nd line to an array
rows++;
}
avg = averageNum(age[], rows); // Function call with the numbers from the array and the variable rows as a pointer
cout << "Average age equals: " << avg << endl;
}
this is one of many possible solutions for your problem:
int main()
{
// Opens a stream to get data from the document
ifstream elevInfo("elevinfo.txt");
// Error message if the file couldn't be found
if (!elevInfo)
{
cout << "Could not find the file elevinfo.txt" << endl;
return (1);
}
int sum = 0;
int lineCounter = 0;
// loop till end of file
while (!elevInfo.eof())
{
// prepare buffer
char line[30];
// read line into buffer
elevInfo.getline(line, 30);
// do this every second line
if (lineCounter % 2 == 1)
{
// get age as int using function atoi()
int age = atoi(line);
// increase sum by the current age
sum += age;
}
// increment line-counter
lineCounter++;
}
// calculate the average
// divide lineCounter by 2 because only every second line in your file contains an age
double avg = sum / (lineCounter / 2.0);
cout << "Average age equals: " << avg << endl;
return 0;
}
As you can see it also doesn't need the function averageNum.
I'm really confused. I have to make this lab for a class and I can't seem to have the search only display one result but all of the months of the year. I also can't seem to figure out why its not displaying the TotalRainfall when I input 0 into the month of the year.
Thank you.
#include <iostream>
#include <fstream>
const int MaxSize = 12; //How many weather lines will be available.
using namespace std;
struct WeatherInformation
{
int Month; //Months of the year
float TotalMonthsRainfall; //Total amount of rainfall
float HighTemp; //The Highest temperature of the month.
float LowTemp; //The Lowest temperature of the month.
float AverageTemp; //The Average temperature of the month.
};
WeatherInformation WeatherArray[MaxSize]; //Declaring a month array of MaxSize
void ReadFile(ifstream& MyinFile, WeatherInformation WeatherArray[]);
void WeatherMonthSearch (WeatherInformation WeatherArray[]);
int main()
{
float TotalRainfall = 0;
int count = 1; //Counts how many times the for loop goes.
int MonthOfWeather; //User input of the month.
char ProgramRedo; //User input if they want to reuse the program.
char exit_char; //User input to exit the program.
ifstream MyinFile; //Variable that uses file.
ReadFile (MyinFile, WeatherArray); //Call ReadFile Function
WeatherMonthSearch (WeatherArray); //Call WeatherMonthSearch Function
MyinFile.close(); //Closes file.
}
//Brett Holmes
//4/30/2013
//PreCondition:You need a file labeled weather.dat
//PostCondition: It puts the file variables into an array.
void ReadFile(ifstream& MyinFile, WeatherInformation WeatherArray[])
{
float TotalRainfall = 0;
char exit_char;
int count = 0;
int Month = 0;
cout << "Your Weather Machine" << endl << endl;
MyinFile.open("weather.dat");
if (!MyinFile)
{ //no
cout << "Can't open input file." << endl; //Tests the right file.
char exit_char; //End Program
cout << "Press any key to exit" << endl;
cin >> exit_char;
}
for(count = 1; count < MaxSize; count++) //Puts the file variables in the array.
{
WeatherArray[count].Month = WeatherArray[count].Month + 1;
MyinFile >> WeatherArray[count].TotalMonthsRainfall;
MyinFile >> WeatherArray[count].HighTemp;
MyinFile >> WeatherArray[count].LowTemp;
(WeatherArray[count].AverageTemp = ((WeatherArray[count].HighTemp + WeatherArray[count].LowTemp)/2));
(TotalRainfall = TotalRainfall + WeatherArray[count].TotalMonthsRainfall);
}
}
//Brett Holmes
//4/30/13
//PreCondition:You need to have the months already put into an array in a struct.
//PostCondition:Outputs the rainfall stats the user puts in then asks to run again.
//Outputs a error message if they type in the month wrong.
void WeatherMonthSearch (WeatherInformation WeatherArray[])
{
float TotalRainfall;
int months;
int MonthOfWeather;
char ProgramRedo;
do
{
bool MonthFound = false;
cout << "Please input the number of the Month. Ex. 1=Jan. 2=Feb. etc \n\n";
cin >> MonthOfWeather;
for(int i = 1; i <= MaxSize; i++)
{
months = WeatherArray[i].Month;
if(months == MonthOfWeather ) //Finds the artist and outputs the results
{
cout << "\nTotal Months Rainfall: " << WeatherArray[i].TotalMonthsRainfall << " \n";
cout << "Highest Temperature: " << WeatherArray[i].HighTemp << " \n";
cout << "Lowest Temperature: " << WeatherArray[i].LowTemp << " \n";
cout << "Average Temperature: " << WeatherArray[i].AverageTemp << " \n";
MonthOfWeather = true;
}
}
if(MonthOfWeather == 0)
{
cout << "The total rainfall for the year is: " << TotalRainfall << ".";
}
if(MonthFound == false)
{
cout << "\nMonth Number error. Month not found. Try again.\n\n";
MonthOfWeather = false;
}
cout << "Would you like to look up another month of weather?\n";
cout << "Enter a 'Y' if yes and 'N' if no.\n";
cin >> ProgramRedo;
}while(ProgramRedo == 'Y');
}
Several obvious problems:
Arrays in C++ is 0-based, so your for loop is off-by-one. In your search function, for(int i = 1; i <= MaxSize; i++) should be for(int i = 0; i < MaxSize; i++). Similarly, in your read function, for(count = 1; count < MaxSize; count++) should be for(count = 0; count < MaxSize; count++) (If you want to skip index 0 because you are using it as a signal value, then you should set MaxSize to 13 and have the loop start at 1.)
Why are you assigning a boolean to MonthOfWeather? Do you mean MonthFound?
You read function is not setting the months correctly. WeatherArray[count].Month = WeatherArray[count].Month + 1; should be WeatherArray[count].Month = count; if you are using a 1-based loop or WeatherArray[count].Month = count + 1; if the loop is 0-based.
You calculated your total rainfall in the read function, but the result is stored in a local variable so it's lost when the read is done. Either make TotalRainfall a global variable or do your calculations in your search function.
There are a lot of redundant variable definitions: for example, your weather data array is a global so there is no reason to actually pass it around; exit_char is declared twice in your read function; the first five lines of your main() declared variables that you never used.
Also, your read function does not actually exit the program on failure - it even still attempts to read from the stream and then call your search function! If error-checking is a requirement, you should either have the read function return a boolean and check that the read function succeeded before calling your search function, or simply call std::exit after that cin >> exit_char;.
So, one problem you have is that you have local variables that appear in multiple places, but appears like you expect them to actually contain the same information.
For example, I see three different TotalRainFall. One in main, which is just there, not used for anything, one in ReadFile which is calculated, and one in WeatherMonthSearch, which is not set to anything.
I suspect you want all three of these to actually do something. One way to achieve that would be to remove the local ones in ReadFile and WeatherMonthSearch, and instead pass in the one from main (as a reference into ReadFile).
There's also a few places where you use variables without initializing them. Make it a habit to initialize EVERYTHING and EVERYWHERE!
Enable warnings in your compiler - if you have any form or reasonably new compiler (gcc or MS Visual Studio of recent vintage), it should tell you at least some of these things.