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...
Related
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.
So the program should ask a day as an input then it should represent it as an integer value (eg.
0 = Sunday or 1 = Monday and etc) then the user enters n number of days (like say 10 days) and the program has to find what day(from Sunday to Saturday) is after 10 days. (I know I can solve it using loop pretty easily but I am preferring not to use it, thanks.)
#include <iostream>
#include <string>
int main() {
std::string today;
std::cout <<"What day is today: " << std::endl;
std::getline (std::cin, today);
int d_ay;
std::cout << "How many days to add ";
std::cin >> d_ay;
if (today == "Monday" or 1){
today = 1 or "Monday";
}
if (today == "Tuesday"){
today = 2;
}
if (today == "Wednesday"){
today = 3;
}
if (today == "Thursday"){
today = 4;
}
if (today == "Friday"){
today = 5;
}
if (today == "saturday"){
today = 6;
}
if (today == "Sunday"){
today = 0;
}
int meet;
if(d_ay > 6){
if (d_ay > 20){
meet = (today + d_ay)/6;
}
}
return 0;
}
This is how far I have got.
Since the cycle of "Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday" repeats every 7 days, you only need 7 cases for d_ay.
However, this process can be made even more elegant by using the concept of modulo. Mods are represented by the % symbol in C++, and they are defined such that:
a % b = the remainder when a is divided by b.
For example, 4 % 3 = 1 and 4 % 2 = 0.
Now, we can write a revised program:
#include <iostream>
#include <string>
using namespace std;
int main(){
vector <string> days = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
// Input
string today;
cout << "Enter today: ";
cin >> today;
int increment;
cout << "Enter the increment: ";
cin >> increment;
cout << days[(i + increment)%7] << endl;
return 0;
}
If I were you I would just make an array of strings for each day of the week and create a placement unit variable like an int to keep track of where u are. So for example monday would be unit 1 because the week starts on sunday. Just add how ever many days to the index and if the new day is over 7 than just find the remainder after you divide it by seven. Then just print out the day of the week with the index number showing which day of the week it is in the array.
How can I get specified number?
For example, the number that a user enters is 4568962358.
I want to save the "96" in a variable; how do I get just the 96 or 23?
This is the real problem:
An important shipping company is making the annual inventory of the goods they have in their warehouse, for which they have implemented a system of codes that are assigned to each good that is in said warehouse. This code, which consists of 16 digits, contains the following information: unique number, indicator of whether it is fragile or not, place of origin of the property and expiration date of the property.
The assigned code structure is UUUFPPPPDDMMAAAA where:
UUU: unique number of the good.
F: digit that indicates if the good is fragile or not. If it is 0 it means that it is fragile.
PPPP: ASCII codes of the two letters that identify the country of origin of the good.
DD: Good's due date.
MM: Month of the expiration of the good.
AAAA: Year of expiration of the good.
You are asked to create a C ++ program that receives the assigned code as data and then prints the following data as shown in the example.
Enter the code: 1120677212042015
Then the program must print: Unique number: 112.
Fragile(N: No; S: Yes): S .
Country of origin: CH .
Day, month and year of expiration: 04-12-2015 .
Well it is outdated to date (N : No; S: Yes): S.
In the solution of the problem you will not be able to make use of selective structures.
Version 1
#include "stdafx.h"
#include "conio.h"
#include "iostream"
using namespace System;
using namespace std;
int main()
{
int code;
int UUU;
int F;
int PP1,PP2;
int DD;
int MM;
int AAAA;
cout << "Enter the code: "; cin >> code; // 1120677212042015
// ...code needed here
UUU = int(code / 10000000000000);
cout << "\nRESULTS" << endl;
cout << "\nUnique number: " << UUU << endl; // prints 112
_getch();
return 0;
}
Version 2
I'm not able to do the next parts; please help!
#include "stdafx.h"
#include "conio.h"
#include "iostream"
using namespace System;
using namespace std;
int main()
{
double code;
double UUU;
double F;
double PP1,PP2;
double DD;
double MM;
double AAAA;
cout << "Enter the code: "; cin >> code; // 1120677212042015
UUU = int(code / 10000000000000);
PP1 = int(code / 10000000000) % 100;
PP2 = int(code / 100000000) % 100;
DD = int(code / 1000000) % 100;
cout << "\nRESULTS" << endl;
cout << "\nUnique number: " << UUU << endl; // 112
cout << "Country of origin: " << (char)PP1 << (char)PP2<<endl; //CH
cout << "Day, Month and Year of expiration: " << DD; // 12/../....
_getch();
return 0;
}
One way is using substr concept.
For example, if user enters input as 1120677212042015, then read it into a string and divide the string into sub-strings according to the format UUUFPPPPDDMMAAAA .
std::string sUserCode = "1120677212042015";
std::string sUniqueNumber = str.substr (0,3);
int iUniqueNumber = stoi(sUniqueNumber);
This is one of those occasions where the C library comes in handy :
int UUU, F, PP1, PP2, DD, MM, AAAA;
cout << "Enter the code: "; // 1120677212042015
scanf("%3d %1d %2d %2d %2d %2d %4d", &UUU, &F, &PP1, &PP2, &DD, &MM, &AAAA);
This captures all the values. The spaces in the format string are not necessary, but makes it easier to read.
u can use % and / to do this
4568962358 / 10000 = 456896 %100 = 96
or you can put it in a array and show the part of integer that u want.
int n = 4568962358;
int a[10];
for (int i = 0; i<10 ; i++)
{
a[i] = n%10;
n /= 10;
}
search your question in stack over flow.
these questions have good answers.
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;
}
Currently, I am taking a C++ course at my local college, and was given a debugging assignment. In the instructions for this assignment, I was told that the only thing really wrong with this code, is that the conditions for the nested if-else-if statements on lines 82-89 are redundant, however, I cannot see another way to get the same results without having those conditions stay the same...any tips or such would be greatly appreciated!
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
const int BASE_COST = 10;
const int LOW_LIMIT = 20;
const int MID_LIMIT = 40;
const int HIGH_LIMIT = 60;
const double LOW_CHECKS = .10;
const double MIDLOW_CHECKS = .08;
const double MIDHIGH_CHECKS = .06;
const double HIGH_CHECKS = .04;
int main()
{
int numOfChecks;
double multiplierValue;
double totalFee;
cout << fixed << showpoint;
cout << setprecision(2);
cout << "Please enter the number of checks you used this month: ";
cin >> numOfChecks;
if(numOfChecks < 0)
{
cout << "Number of checks can't be negative. Program ends.\n";
exit(1); //terminate the program with error code 1
}
//the following line runs only if the program did not terminate, so start over if-else
if(numOfChecks < LOW_LIMIT)
multiplierValue = LOW_CHECKS;
else if(numOfChecks < MID_LIMIT)
multiplierValue = MIDLOW_CHECKS;
else if(numOfChecks >= MID_LIMIT && numOfChecks < HIGH_LIMIT)
multiplierValue = MIDHIGH_CHECKS;
else if (numOfChecks >= HIGH_LIMIT)
multiplierValue = HIGH_CHECKS;
totalFee = BASE_COST + numOfChecks * multiplierValue;
cout << "Your total for this month is $" << totalFee;
_getch();
return 0;
}
This part else if(numOfChecks >= MID_LIMIT && numOfChecks < HIGH_LIMIT) looks redundant. Provided you keep the order of the range checks, it can be simplified to just else if (numOfChecks < HIGH_LIMIT), same as the one following it (which is just not needed) so that the whole piece looks like:
//the following line runs only if the program did not terminate, so start over if-else
if (numOfChecks < LOW_LIMIT)
multiplierValue = LOW_CHECKS;
else if (numOfChecks < MID_LIMIT)
multiplierValue = MIDLOW_CHECKS;
else if (numOfChecks < HIGH_LIMIT)
multiplierValue = MIDHIGH_CHECKS;
else
multiplierValue = HIGH_CHECKS;
Indeed, all the conditions are redundant: use an algorithm :)
Live On Coliru
#include <iomanip>
#include <map>
#include <iostream>
namespace {
using Threshold = unsigned;
using Rate = double;
static Rate constexpr BASE_COST = 10.0;
std::map<Threshold, Rate, std::greater<> > const tariffs {
{ 0, .10},
{20, .08},
{40, .06},
{60, .04},
};
double fee(unsigned numOfChecks) {
auto rate = tariffs.lower_bound(numOfChecks);
return BASE_COST + rate->second * numOfChecks;
}
}
int main() {
unsigned numOfChecks;
std::cout << "Please enter the number of checks you used this month: ";
if (std::cin >> numOfChecks) {
std::cout
<< "\nYour total for this month is $"
<< std::fixed << std::showpoint << std::setprecision(2) << fee(numOfChecks)
<< std::endl;
} else {
std::cout << "Invalid input\n";
return 1;
}
}
Prints e.g.
Please enter the number of checks you used this month: 10
Your total for this month is $11.00
Please enter the number of checks you used this month: 20
Your total for this month is $11.60
Please enter the number of checks you used this month: 30
Your total for this month is $12.40
Please enter the number of checks you used this month: 40
Your total for this month is $12.40
Please enter the number of checks you used this month: 50
Your total for this month is $13.00
Please enter the number of checks you used this month: 60
Your total for this month is $12.40
Please enter the number of checks you used this month: 70
Your total for this month is $12.80
Please enter the number of checks you used this month: 80
Your total for this month is $13.20
Please enter the number of checks you used this month: 90
Your total for this month is $13.60
Please enter the number of checks you used this month: 100
Your total for this month is $14.00