Error with vectors, switch statement, dataFile
When compiling my code case 2 results in me getting an error but if i comment
case 2 out my code works fine. I am confused what i did wrong.
my newdata.text file says 1000, 2000, 3000, 4000, 5000
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main()
{
int true1 = 0, true2 = 0;
int c = 0;
int salary;
std::vector<int> data;
int largest = data[0];
unsigned int lowest = data[0];
char answer;
std::ifstream dataFile;
dataFile.open("newdata.txt");
if (!dataFile)
std::cout << "Data file not found" << std::endl;
std::string value;
while (getline(dataFile, value, ','))
{
data.push_back(std::stoi(value)); //string to interger
}
dataFile.close(); //close the text file
do
{
std::cout << "Please select 1,2,3, or 4: " << std::endl;
std::cout << "Search salary - Enter 1" << std::endl;
std::cout << "Generate stats file - Enter 2" << std::endl;
std::cout << "Print salaries - Enter 3" << std::endl;
std::cout << "Quit - Enter 4" << std::endl;
std::cin >> c; //choose a option
switch (c)
{
case 1: std::cout << "What is the salary?" << std::endl; //1st case
std::cin >> salary;
for (int x = 0; x <= 4; x++)
{
if (salary == data[x])
{
true1 = 1;
}
else
{
true2 = 1;
}
}
if (true1 == true2)
{
std::cout << "Matching salary found" << std::endl;
}
else
{
std::cout << "You entered the wrong salary\n";
}
break;
case 2:
{
for (unsigned int y = 0; y <= 4; y++)
{
if (data[y] > largest)
{
largest = data[y];
}
}
std::cout << "Highest score is " << largest << std::endl;
for (unsigned int z = 0; z <= 4; z++)
{
if (data[z] < lowest)
{
lowest = data[z];
}
}
std::cout << "Lowest score is " << lowest << std::endl;
std::ofstream FileData("stats.txt");
FileData << largest << lowest;
FileData.close();
std::cout << "Stats.txt has been generated" << std::endl;
std::cout << "Highest and Lowest salaries are: " << largest << " " << lowest << std::endl;
break;
}
case 3: std::cout << "All salaries: " << std::endl;
for (int q = 0; q <= 4; q++)
{
std::cout << data[q] << std::endl;
}
break;
case 4: exit(0); break;
}
std::cout << "Do you want to continue (y/n)" << std::endl;
std::cin >> answer;
answer = tolower(answer);
}
while (answer == 'y');
return 0;
}
|
Last edited on
You blindly access values in a vector without making sure those values even exist.
Topic archived. No new replies allowed.