Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here is an assignment I an having trouble with. The code I have for the assignment is below. Im not sure why Im not reading in the data from the txt file. can anyone take a look at the assignment and my code and point me in the right direstion?
Assignment
Service Calls Company Report
The OK-Service Handlers Company handles daily service calls from customers, phone calls. The company handles folk’s problems over the phone. The powers to be need a summary on the calls made in a given month.
The data collected is each day’s service calls that come in and is recorded in a file named SericeCalls.txt. I will put the file out on Blackboard under Assignments.
The data indicates the type of service call made and the number of minutes that service call lasted. The company handles several different kinds of calls and each day there will be several different entries for a given call for a given day. The input will be two numbers per line where the first number is the type of service call and the second is the number of minutes that call lasted. Each input line is a record of one service call. There are 25 different types of service rendered and are numbered 1 to 25.
For example:
3 30 service number 3 and lasted 30 min.
21 45 service number 21 lasted 45 min.
6 28 service number 6 lasted 28 min.
etc..
The company can handle up to 25 different kinds of services. The input file is one month of data.
You are to count the number of service calls for each type of service handle and the number of minutes the call took.
The report should have in it the following information.
The report should have a title and headings.
Output for each type of service call rendered,
the total number of that service call handle for the month,
the total number of minutes spent on that type of service call,
the total number of service calls handle by the company,
the average number of minutes each service type took to handle,
the overall average a service calls took for the month.
I also need to know if and which service call types were not used.
Also tell me which service call took the most time to handle.
Label all output and make it a nice readable report, table format.
You must use arrays, pass arrays, and use functions.
Code
#include "stdafx.h"
#include<iostream>
#include<fstream>
using namespace std;
const int ROWS= 25;
const int COLS = 2;
double input;
ofstream OutFile;
//function prototype
void ReadFile(int[ROWS][2]);
void printArray(int[ROWS][2]);
int main()
{
int ary[ROWS][2];
//open-creates file to print to
OutFile.open ("ServiceCallOutFile.txt");
// Title and Heading
OutFile << "\nMy\n";
OutFile << "\nMonthly Service Call Report \n";
OutFile << "Service call report generated for September 2013\n\n";
cout << "\nMy \n";
cout << "\nMonthly Service Call Report \n";
cout << "Service call reprot generated for Oct. \n\n";
// Call Function 1
ReadFile(ary);
// Call Function 2
printArray(ary);
OutFile<<"\n-----------------------------"<<endl;
cout<<"\n-----------------------------"<<endl;
//closes .txt file
OutFile.close();
cin.get();
cin.get();
return 0;
}
// 1) Open and ReadFile .txt file for array
void ReadFile(int ary[ROWS][2])
{
ifstream infile("ServiceCalls.txt");
for(ROWS;ROWS<25;ROWS+1)
{
cout<<ary[ROWS][COLS];
for (COLS;ROWS<2;COLS+1)
{
infile>>ary[ROWS][COLS];
}
}
infile.close();
}
// 2) Print out all the values in the array with no more than 10 numbers per output line.
void printArray(int ary[ROWS][2])
{
OutFile<< "The numbers in the array are: \n";
cout<< "The numbers in the array are: \n";
for(ROWS;ROWS<25;ROWS+1)
{
cout<<ary[ROWS][COLS];
for (COLS;ROWS<2;COLS+1)
{
OutFile<<ary[ROWS][COLS]<<" "" ";
OutFile<<endl;
cout<<ary[ROWS][COLS]<<" "" ";
cout<<endl;
}
}
}
Input numbers from my .txt file.
17 47
10 43
20 30
4 34
15 22
21 20
3 48
17 38
18 37
12 12
5 5
4 14
8 35
17 29
21 46
2 17
You need to have something changing in the loop to actually execute it. You just used the constants you need for the boundaries and harded coded the constant values which is a Bad Idea. The general form of a for-loop is
for (initialization; condition; advance)
where the initialization can involve the definition of a value. For example, to iterate over the values 0 to 9, you could use the loop
int const boundary(10);
for (int i(0); i != boundary; ++i) {
...
}
Also, your code didn't make any check if your stream is in a good state: you should always check that a value was was actually successfully read from a stream. For example:
if (file >> value) {
use(value);
}
else {
std::cout << "ERROR: failed to read a value from the file\n";
}
Related
Hello and thanks for helping!
So we've got a list of fireworks containing 1) Number in stock 2) Number of fireworks in this package 3) Diameter which equals the noise and
4) The price.
This is the list:
25 17 10 21
10 15 10 18
5 16 10 19
10 15 12 20
15 9 11 12
10 7 28 23
8 7 16 11
10 6 16 10
25 10 18 25
25 12 18 27
10 5 40 35
60 40 5 27
5 25 30 90
50 1 60 8
Our task is to create a shopping list and buy fireworks so we get the highest possible noise. We've got a knapsack capacity of 1000€. We're also supposed to solve this without using tables (so with dynamic programming instead).
I only use one class called Package which contains the four constraints as shown above.
At first I thought it would make sense to try to write an algorithm for a normal knapsack, so just with the price and the diameter (=weight). I tested it with a different list and it worked perfectly fine. I just iterated through all packages and then again used a nested for loop to find the best constellation (exhaustive search). My next idea was to merge the number of fireworks per package with the diameter, because fireworks can only be bought in a full package.
The only thing left which I still haven't found out is what to do with the amount of packages in stock. Like, with my current algorithm it just buys all packages of a firework until the knapsack is full. But obviously that won't be correct.
void knapsack(vector<Package*> stock){
vector<int> indices, tmp_indices;
int noise,tmp_noise= 0;
int price;
for (unsigned int i = 0; i < stock.size(); i++) {
price = stock[i]->price;
noise = stock[i]->diameter*stock[i]->number_fireworks;
indices.push_back(i);
for (unsigned int j = 0; j < stock.size(); j++) {
if (i != j) {
if (price+stock[j]->price<= BUDGET) {
price+=stock[j]->price;
noise+=stock[j]->diameter*stock[j]->number_fireworks;
indices.push_back(j);
}
}
}
// After second loop we have a new possible constellation
// Check if the previous constellation had a lower value and if so, set it to the current one
if (noise > tmp_noise) {
tmp_noise = noise;
tmp_indices.clear();
// tmp save
for (auto &index : indices) {
tmp_indices.push_back(index);
}
}
price= 0;
noise = 0;
indices.clear();
}
// Best constellation found, Print the shopping list
cout << "\Stock.\tNum\Diameter.\Price\n" << endl;
for(unsigned int i = 0; i < tmp_indices.size(); i++) {
cout << stock[tmp_indices[i]]->stock<< "\t";
cout << stock[tmp_indices[i]]->number_fireworks<< "\t";
cout << stock[tmp_indices[i]]->diameter<< "\t";
cout << stock[tmp_indices[i]]->price<< "\t\n";
}
}
We've been told that we should be able to spend exactly 1000€ to get the correct constellation of fireworks. My idea was to add another for loop to iterate through the amount of available packages, but that didn't really work...
This was our first lesson and I'm a bit desperate, because we have only learned how to solve a knapsack problem with 2 constraints and by using a table R.
Edit: Since one user insisted to get a specific question, here it is: Is the idea of using another loop to include the third constraint correct or is there a better/easier way of doing it? Or is it possible that I need a completely different approach for a knapsack with 3 instead of 2 constraints?
Thanks for help in advance
Description:
This program will read a data file that will contain students’ scores for 5
Computer Science (CS) tests. Each student record will contain his/her last name, first
name, numeric student ID, student username, 5 test scores, average for these five scores,
and grade for CS course. The file will be processed by the program and will produce a
report.
The report contains seven parts:
The students’ usernames
The average score for each student’s five tests.
The grade for each student’s CS course.
The average CS scores for the class.
The total number of students with grades A, B, C, D, and F.
The sorted student names and IDs based on user choice: descending or ascending order
of grades.
Search a student grade by entering student user name ID.
(See the attached sample input and output for example.)
Specifications:
All input data will be in an input file. The name of the data file that will be used
for your program MUST BE grade.dat. You may need to create your own
version of grade.dat to test your program before you turn it in. You must also
submit a printout of the contents of this test file when you submit this project.
The student user name is generated by the students’ names and ID numbers
according to the following rule. The student user name will be the first two initials
and the four digits of the student ID number. For example, for student John (last
name), Doe (first name), with ID number 1122, his user name would be: jd1122.
The user names are all lower cases.
Your program needs to use a structure to store the student information including
last name, first name numeric student ID, student user name, 5 test scores,
average for these five scores, and grade for CS course.
Your program needs to write at least three functions in your program: For
example: find average, find grade, search score etc.
2
Your program needs to do input checking: (1) correct input choices for sorting:
ascending or descending; and (2) correct format for user ids: first two are letters
and last four are digits.
Requirements for Submission:
You must
submit your C++ source code, which is .cpp file through myClasses#SU, and hand
in:
Design/pseudocode/hierarchy chart. of your algorithm.
A printed copy of your source code.
Your set of sample input data files
Your set of sample screen outputs corresponding to each input data file.
Program report: state clearly if your program doesn’t work well. What’s the
problem? Or anything you want me to know, for example, you get the help from
other students. You can not copy others’ work. It is individual program
assignment!
You will need to be ready to demo your project and ready to answer any questions
related with the project.
Grading Rubric:
Algorithm design/Pseudocode 10
Correct outputs 20
Structures 20
Functions 10
File reading 10
Input checking 10
Searching and sorting 10
Readability/comments of program (including project report) 10
3
Sample Run
Sample Input File grade.dat contains:
Bonebrake Nicole 1111 90 85 50 78 85
Boyer Dennie 2222 100 90 99 89 88
Bozick Julia 3333 52 85 44 66 87
Carroll Sandra 4444 87 88 95 85 100
Creighton Sarah 5555 91 55 80 88 75
Everett Terry 6666 60 70 59 79 89
Freeman Andrew 7777 92 95 94 96 97
Fugett Brandon 8888 77 88 75 95 80
Here is what I have so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct StudentData
{
string first;
string last;
int studentID;
int exam1;
int exam2;
int exam3;
int exam4;
int exam5;
};
int main()
{
ifstream file;
file.open("grade.dat");
StudentData students[8][8];
file.close();
}
I am having trouble bringing the data out of the file and putting it into an array.
What about the following:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cstdio>
using namespace std;
struct StudentData
{
string first;
string last;
int studentID;
int exam1;
int exam2;
int exam3;
int exam4;
int exam5;
};
int main()
{
ifstream file;
string temp;
char fname[100];
char lname[100];
file.open("grade.dat");
StudentData students[8];
for (int i = 0; i<8; i++)
{
getline(file, temp);
sscanf(temp.c_str(),"%s %s %d %d %d %d %d %d", fname,lname,&students[i].studentID
,&students[i].exam1,&students[i].exam2,
&students[i].exam3,&students[i].exam4,&students[i].exam5);
students[i].first = fname;
students[i].last =lname;
}
file.close();
for (int i = 0; i<8; i++)
{
cout<<students[i].first<<" "<<students[i].last<<" "<<students[i].studentID
<<" "<< students[i].exam1<<" "<< students[i].exam2<<" "<< students[i].exam3
<<" "<< students[i].exam4<<" "<< students[i].exam5<<endl;
}
}
OK, since all you need is a head start, here are some hints:
First of all, your assignment says nothing about 2d arrays, if you are doing it for extra credit or something - don't, it is not mandated neither by your assignment, nor by the actual task at hand.
Second - your problem at hand - reading the file. You should start by reading it one line at a time. The line contains the names, the id and the grades. Once you have the line, you can extract the fields, by say splitting the string at the spacebars. This will give you a string for every field. Then you can assign the student name fields to the strings. There is also a function that converts strings to integers - that will come in handy for the rest of the fields.
Just to make things look a little more professional, you might want to consider using a container class instead of a plain array, std::vector is a good candidate. Also, if you are going to be sorting, you might want to use pointers (preferably smart pointers) and dynamic memory allocation. Also, in order to be able to sort your array, you will need to write functions which compare students based on different criteria. A container will give you an easy way to add and remove students, instead of some stiff static construct.
Every step of the way is already covered in answers here on SO, so all you need to get things done is search whenever you get stuck.
I have a 2D world in my game consisting of tiles. Whenever I make a new world I initialize an array of 48 million tiles
short worldGrid[48000000];
I set the value for all 48 million, then I write those values into a file like this:
std::fstream save("game_save", std::fstream::out);
for (int x = 0; x < 48000000; x++)
{
save << world.worldGrid[x];
save << " ";
}
save.close();
It's 48 million values, each one 2 bytes. So 96 million bytes, or 96 megabtyes. My problem is that this process inside the for loop alone takes 2 minutes to complete on my SSD. I don't feel like it should take 2 minutes and 5 seconds to write 96mb worth of data onto this file. If anyone has any advice I'd really appreciate it.
Try writing the array all at once, instead of 2 bytes-at-a-time..
Something like:
save.write(world.worldGrid, sizeof(worldGrid));
See the docs
I have a vector of structs, with the structs looking like this:
struct myData{
int ID;
int arrivalTime;
int burstTime;
};
After populating my vector with this data:
1 5 16
4 7 12
3 12 4
2 7 8
where each row is an individual struct's ID (arbitrary, doesn't denote order of arrival), arrivalTime and burstTime, how would I use "for" or "while" loops to step through my vector's indices and calculate the data in a way that I could print something like this out?
Time 0 Processor is Idle
Time 5 Process 1 starts running
Time 21 Process 2 is running
Time 29 Process 4 is running
Time 41 Process 3 is running
The way I thought I could do it was to have an integer keep track what the current time is (the current time being the sum of the burst times of processes that have already ran) but I can't seem to figure out an algorithm that accounts for Idle time (when the processor is not doing anything and a new task hasn't arrived yet) as well as keeping track of the other numbers as well. For simplicity's sake I just decided that when two processes arrive at the same time I would process the one with the lower ID number. I know I didn't put much code here to demonstrate what I'm trying to do, but I hope I've explained it fairly clearly. I'm looking for a psuedo-code algorithm solution to this problem, but I wouldn't say no to something that has been coded (In C++?).
As an additional note, in case I wasn't able to convey how I access my data clearly, this:
cout << structVector[0].ID << "\n";
cout << structVector[0].arrivalTime << "\n";
cout << structVector[0].burstTime << "\n";
would print out
1
5
16
Any help in psuedo-code or actual code would be GREATLY appreciated!!! After reading this post over a few times I realize I've been pretty generic with the question, but I would love some help just understanding how to calculate this data.
First, sort the vector based on arrival times.
Then the following code will accomplish what you are looking for.
int i = 0, time = 0;
while (i < vec.size())
{
if (vec[i]. arrivalTime > time)
cout << "Time " << time << "process is idle";
time += vec[i].arrivalTime;
cout << "Time " << time << " Process " << vec[i].ID << " is running" << endl;
time += vec[i].burstTime;
i++;
}
I need to get very basic input from an external file in C++. I tried searching the internet a few times but nothing really applied to what I need. This would be a .txt file that the input it coming from, and it would be filled with lines like this:
131
241
371
481
I have code already to manually get this input, and it looks like this:
using namespace std;
//Gets the initial values from the user.
int control=0;
while (rowb!=0){
cout << "Row: ";
cin >> rowb;
cout << "Column: ";
cin >> columnb;
cout << "Number: ";
cin >> numb;
row[control]=rowb-1;
column[control]=columnb-1;
num[control]=numb;
control++;
}
This is part of a program that solves sudoko boards. The inputed numbers are the initial values that a sudoko board holds, and the user is inputing the row, column, and number that comes from a board.
What I need is to be able to create a .txt file with these numbers stored in rows so that I do not have to enter so many numbers. I have very little idea how to go about doing this. Mainly I'll only be using the txt file for testing my program as I move along with adding more code to it. It takes 150+ entered numbers within my program just to get a single board, and it takes a lot of time. Any accidentally wrong entered value is also a huge problem as I have to start again. So how would I get C++ to read a text file and use those numbers as input?
Aside from the other suggestions, you can simply redirect a file to standard input, like so (where $ is the command prompt):
$ myprogram < mytextfile.txt
That will run myprogram just as normal but take input from mytextfile.txt as if you had typed it in. No need to adjust your own program at all.
(This works on both Unix/Linux systems and on Windows.)
You can open a file for input with std::ifstream from the header <fstream>, then read from it as you would from std::cin.
int main()
{
std::ifstream input("somefile.txt");
int a;
input >> a; // reads a number from somefile.txt
}
Obviously, you can use >> in a loop to read multiple numbers.
Create an std::ifstream object, and read from it just like you would from std::cin. At least if I understand what you're trying to do, the 131 as the first input is really intended to be three separate numbers (1, 3, and 1). If so, it's probably easiest to change your input file a bit to put a space between each:
1 3 1
2 4 1
3 7 1
4 8 1
Personally, I would start with a different format of the file: enter a value for each cell. That is, each row in the input file would represent a row in the sudoko board. Empty fields would use a space character. The immediate advantage is that the input actually pretty much looks like the sudoko board. Also, you would enter at most 90 characters: 9 characters for the board and a newline for each line:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
int main(int ac, char* av[])
{
std::ifstream in(ac == 1? "sudoko.init": av[1]);
char board[9][9];
for (int i(0); i != 9; ++i)
{
in.read(board[i], 9).ignore();
}
if (!in)
{
std::cout << "failed to read the initial board\n";
}
else
{
typedef std::ostream_iterator<char> iterator;
std::fill_n(iterator(std::cout << "board:\n\n+", "+"), 9, '=');
for (int i(0); i != 9; ++i)
{
std::copy(board[i] + 0, board[i] + 9, iterator(std::cout << "\n|", "|"));
std::fill_n(iterator(std::cout << "\n+", "+"), 9, (i + 1) % 3? '-': '=');
}
std::cout << "\n";
}
}
This would take input like this:
4 5 3 8
71 3
16 7
6 4 7
6 8
1 9 5
6 42
5 94
4 7 9 3
Note that each of these lines uses 9 characters. You might want to use something more visible like ..