SIGSTP error in lead game problem of codechef. TLG problem - c++

`
#include<bits/stdc++.h>
#include <iostream>
#include<vector>
using namespace std;
int main() {
// your code goes here
int t;
cin >> t;
vector<int>v1, v2;
v1.push_back(0);
v2.push_back(0);
while (t--)
{
int a, b;
cin >> a >> b;
if (a > b)
v1.push_back(a - b);
else
v2.push_back(b - a);
}
int m1, m2;
if (v1.size() > 1)
m1 = *max_element(v1.begin(), v1.end());
else
m1 = 0;
if (v2.size() > 1)
m2 = *max_element(v2.begin(), v2.end());
else
m2 = 0;
if (m1 > m2)
cout << "1" << " " << m1;
else
cout << "2" << " " << m2;
}
`
this is lead game question in codechef but I am getting SIGSTP error while running code. I am not getting how to overcome this. I have spend my a plenty of time. Can someone help me to getting rid of this problem.I am new in the competitive programming. Please suggest me some resources or lectures on youtube to do better.
Thanks in Advance...

Submitting this code didn't got me SIGSTP but I got Wrong Answer verdict. This is due to the fact that you are not checking the cumulative scores of the players but directly comparing the current scores and pushing them in the vectors accordingly. You can maintain two variables to store the cumulative scores of the players and then check that which player has the current lead. Try the following solution:
int main()
{
int rounds;
cin >> rounds ;
int lead = 0 ;
int player = 0;
int cs1 = 0 , cs2 = 0 ;
while(rounds--){
int p1 , p2 ;
cin >> p1 >> p2 ;
cs1+=p1;
cs2+=p2;
if(cs1 > cs2 && lead < (cs1 - cs2) ){
lead = cs1 - cs2 ;
player = 1;
}
else if(cs2 > cs1 && lead < (cs2 - cs1))
{
lead = cs2 - cs1 ;
player = 2;
}
}
cout << player << " " << lead << endl;
return 0;
}

int main() {
// your code goes here
int n;
cin>>n;
int max=0,player=1;
int cs1=0,cs2=0;
for(int i=0;i<n;i++)
{
int si,ti;
cin>>si>>ti;
cs1=cs1+si;
cs2=cs2+ti;
if(abs(cs1-cs2)>max)
{
max=abs(cs1-cs2);
if(cs1>cs2)
player=1;
else
player=2;
}
}
cout<<player<<" "<<max<<endl;
return 0;
}
Ive provided an alternate approach to the TLG problem. When you get the input compute the cumulative scores then and there itself and later assign the difference to the player who has higher cumulative score.Hope this helps!

Related

Debugger has correct output but normal execution does not

I'm having this strange issue where my code does exactly what I want it to when I run it through my debugger, but it doesn't work when I run it normally. What's stranger is that I am not getting a runtime error either. This is where the issue might be, but I'm not 100% sure on this:
void calcMostMissed (double *ptr, int totalContestants, int arrSize)
{
//output header
cout << endl << "MOST MISSED QUESTIONS" << endl;
//check how many times a question is missed and its percentage, then output it if it's above 60%
double curQuest = *ptr;
int freq = 0;
int j = 0;
double percentMissed;
for (int i = 0; i <= arrSize; i++) //loop through the missed questions array
{
if (*(ptr + i) > 0) //if pointer is pointing at a question number (extra space in array is set to 0)...
{
if (*(ptr + i) == curQuest) //then check how often it occurs in the array
freq++;
}
else //if the pointer is not pointing at a question number anymore...
{
//calculate percent missed and output it if its 60% or greater
percentMissed = (static_cast<double>(freq) / totalContestants) * 100;
if (percentMissed >= 60)
{
cout << static_cast<int>(curQuest) << "\t" << fixed << setprecision(2) << percentMissed << "%" << endl;
}
// check if the question's percentage missed has already been calculated and evaluated
j++;
curQuest = *(ptr + j);
int r = 0;
while (r < j)
{
if (*(ptr + r) == curQuest)
{
if (j < arrSize - 1)
{
j++;
curQuest = *(ptr + j);
}
}
r++;
}
if (!(j == arrSize - 1 && r == arrSize - 1))
{
i = 0;
}
freq = 0;
}
//if the current question variable has been through all missed question, then leave loop
if (curQuest < 1)
{
break;
}
}
}
What this function is supposed to do overall is find the percent missed on all missed questions and output only the ones that are above 60% inclusive.
This is what my debugger outputs (and what I want it to look like):
Enter name of answer key file: batch7a.txt
Enter name of contestant's answers file: allWrongContestants.txt
oo12345678 - 0.00
1 2 3
C A B
A B C
0012387654 - 0.00
1 2 3
C A B
A B C
0012364213 - 0.00
1 2 3
C A B
A B C
Mean: 0.00
Median: 0.00
Mode: 0.00
MOST MISSED QUESTIONS
1 100.00%
2 100.00%
3 100.00%
This is what a normal execution ouputs:
Enter name of answer key file: batch7a.txt
Enter name of contestant's answers file: allWrongContestants.txt
oo12345678 - 0.00
1 2 3
C A B
A B C
0012387654 - 0.00
1 2 3
C A B
A B C
0012364213 - 0.00
1 2 3
C A B
A B C
Mean: 0.00
Median: 0.00
Mode: 0.00
MOST MISSED QUESTIONS
Process returned 0 (0x0) execution time : 14.442 s
Press any key to continue.
My debugger runs through all the way to the end of my program just fine, but for some reason the normal execution is still flawed. Any suggestions are welcome and I'll clarify anything that I may have forgotten to mention.
If it helps, I am using Code::Blocks as my IDE
Some other info about my code: there are 3 questions and all contestants scored a 0% on the test, meaning all questions have the incorrect answers.
Output: The numbers are the contestant's ID, next to that is their score, the list of numbers underneath is the question number they got wrong, underneath that are the contestant's answers, and under that are the correct answers.
This is the function that calls the calcMostMissed function:
void statReport (double *ptr, int totalScores, double *mmqPtr, int arrSize)
{
//calculate mean of scores
double mean = calcMean(ptr, totalScores);
//calculate median of scores
double median = calcMedian(ptr, totalScores);
//calculate mode of scores
double *mode = calcMode(ptr, totalScores);
//output to console the data
cout << "Mean: " << fixed << setprecision(2) << mean << endl;
cout << "Median: " << median << endl;
cout << "Mode: ";
sort(mode, mode + totalScores);
int j = 0;
for (int i = 0; i < totalScores; i++)
{
if (*(mode + i) != -1)
{
if (j == 0)
{
cout << *(mode + i);
}
else
{
cout << ", " << *(mode + i);
}
j++;
}
}
cout << endl;
//call calcMissedQuestions function
calcMostMissed(mmqPtr, totalScores, arrSize);
//delete pointers
delete[] mode;
mode = nullptr;
delete[] mmqPtr;
mmqPtr = nullptr;
}
And this is the main function:
int main()
{
string answerKeyName;
string contestantAnswerName;
ifstream answerKeyFile;
ifstream contestantAnswerFile;
//ask for file names
cout << "Enter name of answer key file: ";
cin >> answerKeyName;
cout << "Enter name of contestant's answers file: ";
cin >> contestantAnswerName;
//check if files can be opened properly
answerKeyFile.open(answerKeyName, ios::binary);
contestantAnswerFile.open(contestantAnswerName, ios::binary);
if(!answerKeyFile)
{
cout << "Answer key file could not be opened" << endl;
exit(EXIT_FAILURE);
}
if (!contestantAnswerFile)
{
cout << "Contestant's answers file could not be opened" << endl;
exit(EXIT_FAILURE);
}
//find how many contestant's there are
int i = 0;
string temp;
while (contestantAnswerFile.good())
{
getline(contestantAnswerFile, temp);
if (temp != "")
{
i++;
}
}
contestantAnswerFile.clear();
contestantAnswerFile.seekg(0, ios::beg);
//create contestant's score array
double *scorePtr = new double[i];
//create pointer for all missed questions
double *mmqPtr = nullptr;
int arrSize;
//compare the contestant's answers to the answer key, then fill array with score
double score;
for (int c = 0; c < i; c++)
{
score = compareAnswers (contestantAnswerFile, answerKeyFile, mmqPtr, i, arrSize);
*(scorePtr + c) = score;
}
//create the statistics report
statReport(scorePtr, i, mmqPtr, arrSize);
//delete dynamically allocated array
delete[] scorePtr;
scorePtr = nullptr;
//close files
answerKeyFile.close();
contestantAnswerFile.close();
return 0;
}
Below is where I think the issue resides, however I still cannot properly compile it because other functions and input files are not provided, probably rightly so in order not to further congest the question:
double *mmqPtr = nullptr; is defined in main(), then it's passed to the statReport() function without having been associated with any object.
Afterward it acts as first parameter for function calcMostMissed() and gets dereferenced inside it, but is still a nullptr, so this produces undefined behaviour.
There is also the issue of an out-of-bounds index inside a loop, as pointed at in the comments.

Creating a vector of structs, expression: vector subscript out of range

I am very new to c++ and currently trying to complete a few little challenges to get up to speed with the simpler aspects.
I'm trying to create an array (found info to suggest vectors are the same and better) of structs to hold data about 10 people. Each person has an "index" (to identify person1, person2, person3, etc..), a "num" (to store the collected data) and a "rank" (a variable which I intend to use to sort the people using the data collected)
The code doesn't show any errors before compiling, however, when the first piece of data is entered I get the following message:
"Debug Assertion Failed!
Program: C:\WINDOWS\SYSTEM32\MSVCP140D.dll
File: d:\program files\microsoft visual studio\community\vc\tools\msvc\14.12.25827\include\vector
Line: 1795
Expression: vector subscript out of range"
I have tried searching through multiple threads but I can't seem to work out why this problem is occurring.
My code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct person
{
int index; /*person number*/
int num; /*number of pancakes eaten*/
int rank; /*rank used for sorting people*/
};
vector<person> people; /*create a vector (array) of "person"'s*/
void getData()
{
cout << "You will be asked to enter data from 10 different people" << endl;
cout << "\n" << "The question is; 'How many pancakes did they eat for breakfast?'" << endl;
cin.get();
for (int i = 1; i <= 10; i++)
{
system("CLS");
int j;
cout << "Person " << i << " : ";
cin >> j;
person temp;
people.push_back(temp);
people[i].index = i;
people[i].num = j;
people[i].rank = i;
}
}
int main()
{
getData(); /*collect data for the people*/
system("CLS");
cout << "Data Collected : " << endl;
system("pause");
}
Thanks in advance for anyone who can help.
The problem is in your indexing. The index starts at 0 and not 1. So what happens is when you push the first element, it is stored at people[0]. Then you try to access people[1], since i = 1. Hence the subscript is out of range error.
You need to modify the code to be:
....
for (int i = 0; i < 10; i++)
{
system("CLS");
int j;
cout << "Person " << i << " : ";
cin >> j;
person temp;
people.push_back(temp);
people[i].index = i;
people[i].num = j;
people[i].rank = i;
}
....

How to read a txt file into a 2d array

Hey guys I am new to reading txt files to arrays, so I need to read this txt file temperature.txt to a two dimensional array. Here is the file I need to read, and the code I tried writing up it complies but Im not sure if it is reading it correctly
T(F) R1 R2 R3 R4
95.0 95.20 66.10 43.10 29.00
96.0 96.10 67.60 43.50 31.20
97.0 97.40 67.00 43.70 30.50
98.0 97.20 69.10 44.10 30.70
99.0 98.90 68.00 44.70 32.80
100.0 99.50 71.10 45.10 31.50
101.0 101.00 71.20 45.30 31.60
102.0 101.60 71.00 45.70 30.50
103.0 101.80 73.10 46.30 32.50
104.0 103.70 73.50 46.60 32.70
105.0 105.60 72.80 47.10 33.60
UPDATE I re did this again without looking at your answers but will this work ?
using namespace std;
#include<fstream>
#include<iostream>
#include<cmath>
#include<iomanip>
#include<stdlib.h>
int main ()
{
char temp[11] [5];
ifstream tempin ("c:\\mydoc2\\temperaturedata.txt");
tempin>>temp[0]>>temp[1]>>temp[2]>>temp[3]>>temp[4]>>temp[5]>>temp[6]>>temp[7]>>temp[8]
>>temp[9]>>temp[10];
while(!tempin.fail())
{
cout<< temp[0] << " " << temp[1] << " " << temp[2] << " " << temp[3]<< " " << temp[4]<< " " << temp[5] << " " << temp [6] <<
" " << temp [7] << " " << temp[8] << " " << temp[9] << " " << temp[10];
tempin>>temp[0]>>temp[1]>>temp[2]>>temp[3]>>temp[4]>>temp[5]>>temp[6]>>temp[7]
>>temp[8]>>temp[9]>>temp[10];
}
cout << endl << endl;
system("pause");
return 0;
}
You have a string myArray[5]; but you're reading 55 elements - that should not work!
There are lots of errors in your code.
1) You have written a read function but you never call it, so it never executes.
2) There is no 2D array in your code. 2D arrays look like this double myArray[10][10];. (that's a 10 by 10 2D array of doubles).
3) You're trying to read floating point numbers, but your array is an array of strings.
4) Your array is size 5 but you try and read 55 items into it.
5) After you open the file you have an infinite loop which just prints out "No file\n". Not sure why you want to print out error messages in a loop. Normally you just print an error message once.
I could go on, but I think the main point is that you're a beginner, and you currently aren't able to write three lines of code without introducing an error (sorry to be harsh but based on the above that is true). So the important lesson is that you should not try to write more than three lines of code at once.
Try something like this
a) Write some code which opens a file, test it and check that it does open the file
b) Add some code to a) to read one number, test it and check that it does read one number.
c) Replace the read one number code with code that reads a 1D array of numbers. Test it and check that it works.
etc. etc.
The point is to build up gradually to the program you want, and test each stage as you go. I can't emphasise how important that is. Every professional programmer works like this, but because you're a beginner the steps you have to take are much smaller than an experienced programmer.
Try something like this:
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main() {
string line;
ifstream myfile ("C:/temps.txt");
int dim_x = 12;
int dim_y = 5;
double temps[dim_x][dim_y] ;
//init the array if neccesary
for(int x = 0;x<dim_x;x++)
for(int y = 0; y<dim_y;y++)
temps[x][y]=0;
if (myfile.is_open()){
for ( int x=0; getline (myfile,line); x++ ){
int y=0;
istringstream iss(line);
while(iss){
string sub;
iss >> sub;
temps[x][y] = ::atof(sub.c_str());
y++;
}
}
myfile.close();
}
cout << "TEMPS:" << endl;
for(int x = 0;x<dim_x;x++){
for(int y = 0; y<dim_y;y++)
cout<<temps[x][y]<<" ";
cout<<endl;
}
return 0;
}
I made some improvements
#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void read ();
int main ()
{
read();
return 0;
}
void read()
{
ifstream indata(".\\temperaturedata.txt");
if(indata == NULL)
{
cout<< "Opening file failed."<< endl;
return;
}
const int columns = 5;
const int rows = 11;
double myArray[rows][columns];
string tmp;
getline(indata, tmp);
for(int i = 0; i < rows; ++i)
{
for (int j = 0; j < columns; ++j)
{
cout << "\t" << flush;
indata >> myArray[i][j];
cout.setf(ios::fixed);
cout << setprecision(2) << myArray[i][j] <<flush;
}
cout << endl;
}
indata.close();
}
If the content of your file is like this:
95.0 95.20 66.10 43.10 29.00
96.0 96.10 67.60 43.50 31.20
97.0 97.40 67.00 43.70 30.50
98.0 97.20 69.10 44.10 30.70
99.0 98.90 68.00 44.70 32.80
100.0 99.50 71.10 45.10 31.50
101.0 101.00 71.20 45.30 31.60
102.0 101.60 71.00 45.70 30.50
103.0 101.80 73.10 46.30 32.50
104.0 103.70 73.50 46.60 32.70
105.0 105.60 72.80 47.10 33.60
then, it's quite easy for you to get these values. But there are some errors in your code:
while(!indata.fail()) : This line will cause a dead loop. Use if(!indata) instead.
You will need a 2-dimension array of type double instead of string
Here is what could work:
#include<fstream>
#include<iostream>
#include<cmath>
#include<iomanip>
#include<stdlib.h>
using namespace std;
void read ();
int main ()
{
read();
system("PAUSE");
return 0;
}
void read()
{
ifstream indata("E:\\temperature.txt"); //that's my path,you should use yours.
if(!indata)
{
cout<<"No file."<< endl;
}
if(indata.is_open())
{
double myArray[11][5];
for(int i = 0; i < 11; ++i)
{
for(int j = 0; j < 5; ++j)
{
indata >> myArray[i][j];
//cout<<myArray[i][j]<<"\t";
}
//cout<<endl;
}
}
}
This could work when your txt file doesn't include the first line:T(F) R1 R2 R3 R4, if this line did exit,you should use getline() to move your file pointer to the second line, where you could read the data.

Print numbers in range of two user-input values with while loop

I feel like I might be missing something here, but something is telling me that I might just be making this more difficult that it has to be, but from the book, "C++ Primer, 5th ed.," I'm stuck on this problem:
Exercise 1.11: Write a program that prompts the user for two integers.
Print each number in the range specified by those two integers.
Up until this time in the book, the only loop being used is the while loop, and no conditional expressions, like if, have been introduced. The problem would be simple if it were not for the fact that a user could put the values into the integers asked for in ascending or descending order, so simple subtraction WOULD find the difference, but without testing which way to increment.
How could I absolutely print the range between the numbers, guaranteeing not to just increment towards infinity without testing the outcome of such math and/or without comparing the two numbers? This is what I have; it works when the first value: v1 is less than or equal to the second: v2, but not otherwise:
#include <iostream>
int main()
{
int v1 = 0, v2 = 0;
std::cout << "Enter two integers to find numbers in their range (inclusive): "
<< endl;
std::cin >> v1 >> v2;
while (v1 <= v2)
{
std::cout << v1;
++ v1;
}
return 0;
}
Any help would be greatly appreciated!
Here is a simple rewrite where you use min and max to determine the range you want to iterate on:
#include <iostream>
int main()
{
int v1 = 0, v2 = 0;
std::cout << "Enter two integers to find numbers in their range (inclusive): " << std::endl;
std::cin >> v1 >> v2;
int current = std::min(v1, v2);
int max = std::max(v1, v2);
while (current <= max)
{
std::cout << current << std::endl;
++ current;
}
return 0;
}
This also allows you to keep the two inputs "intact", because you're using another variable to iterate on the values.
Also note that the ++current could be done on the exact same line it is printed if it was replaced by current++. The later would return the current value of current and THEN increment it.
Edit
Here's what Michael suggested I believe, in working code:
#include <iostream>
int main()
{
int v1 = 0, v2 = 0;
std::cout << "Enter two integers to find numbers in their range (inclusive): " << std::endl;
std::cin >> v1 >> v2;
int increment = (v2 - v1) / std::abs(v2 - v1);
int current = v1;
int max = v2 + increment;
while (current != max)
{
std::cout << current << std::endl;
current += increment;
}
return 0;
}
You can use (v2-v1)/abs(v2-v1) or some such for increment. (provided they're not equal). And for loop condition you may check if current number is still in between, like (v1<=v && v<=v2) || (v2<=v && v<=v1).
And to avoid the case of zero, I'd turn it into do while loop and use v1!=v2 && ... as a condition.
To sum it all up:
int v = v1;
do {
std::cout << v << std::endl;
}while( v1!=v2 && ( (v1<=(v+=(v2-v1)/std::abs(v2-v1)) && v<=v2) || (v2<=v && v<=v1) ) );
P.S. I trust you can resolve the input issue mentioned in comments and in the other answer on your own.
I tried my amateur way and got the result. I hope it will be helpful.
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int val;
cout << "Please enter small value "<< endl;
cin >> a;
cout << "Please enter bigger value than the last one " << endl;
cin >> b;
while (val>a)
{
val = --b;
cout << "The numbers between a & b are "<< val << endl;
}
return 0;
}
Since I still remember this problem from the C++ Primer, I think the way they wanted you to solve it was with the basics of programming they provided you until then.
In my opinion it should have been solved like this, if this was this exact problem from this book:
#include <iostream>
int main()
{
int v1 = 0, v2 = 0;
std::cout << "Enter 2 numbers" << std::endl;
std::cin >> v1 >> v2;
while (v1 < v2) {
std::cout << v1 << std::endl;
++v1;
}
}

I'm getting a weird error for a program that seems like it should "just work."

I present to you all a program I'm working on for my college programming course. I still have a little ways to go before it completely meets my assignment's requirements, but I've gotten a basic draft of the program error-free (supposedly) and it appears to run… but then it suddenly kicks me into Xcode's debugger and gives me:
Thread 1: EXC_BAD_ACCESS(code=2, address=0x7fff95c1e5f5)
Here's the command line output, up until it kicks me out:
-----------------------
Quarterly_sales_taxator
-----------------------
How many company divisions will we be dealing with? 2
Am I correct in assuming that there are 4 sales quarters? yes
Please enter the sales Company Division #1 brought in for Sales Quarter #1 20
(lldb)
Here's my code:
//
// quarterly_sales_taxator.cpp
// Ch. 7 program #7
//
// Created by John Doe on 11/27/12.
//
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;
void read_company_divisions_and_sales_quarters(double **, int, int);
//void write_company_divisions_and_sales_quarters_to_array(double **, int, int); // This will be used later on to read data from a file.
void display_quarterly_sales_array(double **, int, int);
string temp; // A global temporary placeholder variable; I use this several times.
int main()
{
int COMPANY_DIVISIONS,
SALES_QUARTERS = 4;
double **quarterly_sales_form;
cout << "\n\n-----------------------\nQuarterly_sales_taxator\n-----------------------\n\n";
cout << "\nHow many company divisions will we be dealing with? ";
getline(cin, temp);
stringstream(temp)>>COMPANY_DIVISIONS;
while (COMPANY_DIVISIONS < 1 || isdigit(COMPANY_DIVISIONS == false))
{
cout << "\n\n------"
<< "\nError:"
<< "\n------"
<< "\n\nYou have entered an invalid choice."
<< "\nPlease type a number greater than zero. ";
getline(cin, temp);
stringstream(temp)>>COMPANY_DIVISIONS;
}
cout << "\n\nAm I correct in assuming that there are 4 sales quarters? ";
getline(cin, temp);
// Convert to uppercase.
for (int count = 0; count < temp.length(); count ++)
{
temp[count] = toupper(temp[count]);
}
if (temp == "NO" || temp == "NOPE" || temp == "INCORRECT" || temp == "YOU ARE NOT" || temp == "YOU ARE INCORRECT" || temp == "NEGATIVE" || temp == "NEGATORY")
{
cout << "\nOk, then how many sales quarters are we dealing with? ";
getline(cin, temp);
stringstream(temp)>>SALES_QUARTERS;
}
cout << endl << endl;
// This sets up the 2d array.
quarterly_sales_form = new double *[COMPANY_DIVISIONS];
for (int count = 0; count < COMPANY_DIVISIONS; count ++)
{ quarterly_sales_form[COMPANY_DIVISIONS] = new double [SALES_QUARTERS]; }
read_company_divisions_and_sales_quarters(quarterly_sales_form, COMPANY_DIVISIONS, SALES_QUARTERS);
// write_company_divisions_and_sales_quarters_to_array(quarterly_sales_form, COMPANY_DIVISIONS, SALES_QUARTERS); // I'll add this feature later.
cout << "\n\nHere's what you entered:\n\n";
display_quarterly_sales_array(quarterly_sales_form, COMPANY_DIVISIONS, SALES_QUARTERS);
// Since we used a series of pointers, we need to free the allocated space back up.
for (int count = 0; count < COMPANY_DIVISIONS; count ++)
{ delete[] quarterly_sales_form[COMPANY_DIVISIONS]; }
delete[] quarterly_sales_form;
return 0;
}
/*############################################
# read_company_divisions_and_sales_quarters #
############################################*/
void read_company_divisions_and_sales_quarters(double **array, int DIVISIONS, int QUARTERS)
{
for (int count = 0; count < QUARTERS; count++)
{
for (int index = 0; index < DIVISIONS; index++)
{
cout << "\nPlease enter the sales Company Division #" << count+1 << " brought in for Sales Quarter #" << index+1 << " ";
getline(cin, temp);
stringstream(temp) >> array[count][index];
}
}
}
/*################################
# display_quarterly_sales_array #
#################################*/
void display_quarterly_sales_array(double **array, int DIVISIONS, int QUARTERS)
{
for (int count = 0; count < DIVISIONS; count++)
{
cout << "\nCompany division #" << count+1 << ":\n";
for (int index = 0; index < QUARTERS; index++)
{ cout << array[count][index] << ", "; }
}
}
Can some kind soul please tell me what I'm doing wrong?
{ quarterly_sales_form[COMPANY_DIVISIONS] = new double [SALES_QUARTERS]; }
In this line, COMPANY_DIVISIONS should be count.
In addition to what Dan Hulme said, it seems this line
stringstream(temp) >> array[count][index];
should really be
std::istringstream(temp) >> std::skipws >> array[index][count];
In addition to using std::istringstream rather than std::stringstream and making sure that an lvalue is at hand, which isn't strictly needed until the type read becomes more interesting, this also reverses the indices: index runs over COMPANY_DIVISIONS and count over SALES_QUARTERS.
The real question is, of course: Who hands out assignments like this? Pointer manipulations and allocations are best left to low-level library writers. This is C++ not C: we can and should use abstractions. Getting this code exception safe is a major challenge and there is no point in teaching people how to write broken (e.g. exception unsafe) code.