Main never runs? Bubble sort & Selections sort - c++

I can't seem to have any output and unfortunately my teacher can't help me. I'm using xcode and previously we have had to change quite a few things to get programs to work and this time I cannot get anything to happen. At first I had just a bubble sort with six numbers and got it to run, but we then added a selection sort and instead of having numbers, they are read in from a txt file.
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
void bubble(string filename);
void selectionSort(string filename);
const int SIZE = 100000;
int values[SIZE];
// Main
int main()
{
cout << "Beginning set of our bubble sorts. Please stand by... " << endl;
bubble("inOrder.txt");
bubble("revOrder.txt");
bubble("ranOrder1.txt");
bubble("ranOrder2.txt");
cout << "Finished with four bubble sorts. " << endl;
system("PAUSE");
return 0;
}
// Functions
void bubble(string filename)
{
unsigned long int passCount = 0, compCount = 0, swapCount = 0;
int temp;
bool swap;
ifstream fin(filename.c_str());
for ( int j = 0; j < SIZE; j++)
fin >> values[j];
do
{ passCount++;
swap = false;
for (int count = 0; count < (SIZE -1); count++)
{
compCount++;
if(values[count] > values[count + 1])
{
swapCount++;
temp = values[count];
values[count] = values[count + 1];
values[count + 1] = temp;
swap = true;
}
}
} while (swap);
string outputName = "Bubble" + filename;
ofstream fout(outputName.c_str());
for ( int j = 0; j < SIZE; j++)
fout << values[j] << endl;
cout << "The number of passes is: " << passCount << endl;
cout << "The number of comparious is:" << compCount << endl;
cout << "The number of swaps is: " << swapCount << endl;
}
// Selection
void selectionSort(int array[], int size)
{
int startScan, minIndex, minValue;
for (startScan = 0; startScan < (SIZE - 1); startScan++)
{
minIndex = startScan;
minValue = values[startScan];
for(int index = startScan + 1; index < size; index++)
{
if (values[index] < minValue)
{
minValue = values[index];
minIndex = index;
}
}
values[minIndex = array[startScan]];
values[startScan] = minValue;
}
}
I tried changing the word 'array' in the sorts to values but it didn't work. And before changing the parameters of the function (and changing the other parts mentioned above) we only had 'string filename' and it worked fine. A lot of things are working for the teacher, but she is using Visual Express. I'm downloading that now but the school internet is extremely slow so I'm trying to work with what I have.
Any suggestions would be greatly appreciated.
Also, the most of the code was done as a class, but not everything worked the same in xcode. As homework I had to add the selection sort and I'm struggling a bit.
EDIT
I'm sorry, I meant I need the output to be files. We had a seperate .cpp file to generate the number needed for the program to do the sorts.
#include <fstream>
#include <iostream>
#include <stdlib.h>
using namespace std;
const int maxSize = 100000;
int main()
{
ofstream fout1("inOrder.txt");
ofstream fout2("revOrder.txt");
ofstream fout3("ranOrder.txt");
ofstream fout4("ranOrder.txt");
cout << "Starting to create 4 output files. . ." << endl;
for (int i = 1; i <= maxSize; i++)
{
fout1 << i << endl;
fout2 << maxSize - i + 1 << endl;
fout3 << rand() << endl;
fout4 << rand() << endl;
}
cout << "Finished creating 4 output files . . ." << endl;
system( "PAUSE");
return 0;
}
All of this code was written by my instructor. For Xcode do I just add the file to the same folder as the main program?

I used to have this issue with opening files using Xcode as well. I've found that if you don't specify a full file path for the txt file you are trying to open, Xcode will check the project folder as expected. The thing is that you have to have added the txt file to the Xcode project, not just drop it in the project folder in Finder.
In Xcode, go to to FILE > Add Files and add the txt files you are trying to open to the project.

Related

How to end a user input array

So this is for a lab assignment and I already have it working, but one thing is bothering me. The assignment involves creating a 1-dimensional array and then manipulating it. I am supposed to allow a max of 100 inputs but the user does not have to use all 100. Right now, I am using a while statement to either break or allow another input to be entered. To break the statement, you have to enter a negative number (this is what I don't like and want to change). What other options are there to end the user input, once they are done entering their numbers? Is it possible to end the loop once you hit enter with nothing typed?
I have searched stackoverflow for the last 3 days and found some compelling stuff but could never get it to work.
Note, I get the void function is redundant here but that's besides the point (unless it actually affects my ability to achieve what I want).
Also, thanks in advance.
here is my code so far (my while statement is in the main)... be kind I'm a newbie to coding.
#include <iostream>
using namespace std;
void reverseElements(int array[], int size)
{
int tmp;
int j;
int i = size;
j = i - 1;
i = 0;
while (i < j)
{
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
i++;
j--;
}
cout << "I will now reverse the elements of the array." << endl;
cout << endl;
for (i = 0; i < size; i++)
{
cout << array[i] << " " << endl;
}
}
int main()
{
const int NUM_ELEMENTS = 100;
int iArr[NUM_ELEMENTS];
int i;
int myInput;
cout << "Enter your numbers, then enter a negative number to finish" << endl;
cout << endl;
for (i = 0; i < NUM_ELEMENTS; i++) //loop to obtain input
{
cin >> myInput;
if (myInput < 0) //checks for negative number to end loop
{
break;
}
else //continues to allow input
{
iArr[i] = myInput;
}
}
cout << endl;
reverseElements(iArr, i);
return 0;
}
Probably the easiest solution: let your user choose how many numbers to write before actually writing them.
int readNumbersCount()
{
int const numbersMin = 1;
int const numbersMax = 100;
int numbersCount = -1;
while (numbersCount < numbersMin || numbersCount > numbersMax)
{
std::cout <<
"How many numbers are you going to enter? Choose from " <<
numbersMin << " to " << numbersMax << ":\n";
std::cin >> numbersCount;
}
return numbersCount;
}
int main()
{
int const numbersCount = readNumbersCount();
for (int i = 0; i < numbersCount; ++i)
{
// read the numbers etc.
}
return 0;
}
I wrote readNumbersCount() as a separate function to extract numbersMin and other "one-use" identifiers from main() and to make main()'s numbersCount const.
I have edited the main function a little bit.
Here the user is asked how many elements he wants to enter .
and doing the memory allocation dynamically so as to save space
int main()
{ int n=101;
while(n>100){
cout<<"How many numbers do you want to enter";
cin>>n;
}
int *ptr=new(nothrow)int[n];
for (int i=0;i<n;i++){
cout << "Enter your number" << endl;
cin>>ptr[i];
}
cout << endl;
reverseElements(ptr, n);
return 0;
}

C++ rand() not working with string array

I'm creating a small program that allows the user to input 3 names (or whatever string they want). The program should then display all three strings (which is working), then it should use the rand() function to randomly display one of the three strings. This is the part that isn't functioning properly.
#include <iostream>
#include <string>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
int name = rand() % (2 + 1 - 0) + 0;
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}
I had it set up differently before, and it gave me an error, but after changing it to what it is now, it always gives me the last element [2].
Is this a code error, or is it just that rand() always gives the same output on the same system?
After some discussion in the comments, it became apparent that the issue was that I was not seeding the rand() function. Below is part of the code that was not functioning, corrected.
(Also, as a sidenote, to use the time() function, <ctime> or <time.h> has to be included.)
srand(time(NULL));
int name = rand() % 3;
cout << names[name];
(Thanks to #manni66 for pointing out that it was useless to include an overly complicated calculation to get the range for rand(), as it just had to be a single integer.
seeding with current time works :
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
srand(time(NULL)); // use current time as seed for random generator
int name = rand() % 3 ;
printf(" random %i \n", name);
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}

read int per line c++ error needs solution

hey guys I need help for my read code seems not working properly here's the code. The problem is as shown in the picture, the compiler are supposed to display all 1 million int value but it seems that my write or the display code was wrong. It shows nothing like it's not even reading.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
#include <omp.h>
#include <ctime>
#include <cstdlib>
using namespace std;
int* CreateArray( int*);
void shellSortParallel( int*, int);
void shellSortSequential(int*, int);
void InsertSort( int*, int, int, int);
int main()
{
int array_size = 1000000;
int n=0;
int* arr=new int[array_size];
ifstream fin("OUTPUT1.txt");
if(! fin)
{
cout << "File could not be opened." << endl;
}
else
{
cout << "File Opened successfully!!!. Reading data from file into array" << endl;
int data;
while(fin>>data)
{
arr[n] = data;
n++;
}
cout << "Displaying Array..." << endl << endl;
for(int i = 0; i < array_size; i++)
{
cout << arr[i];
}
}
fin.close();
int length = 1000000;
double endTime = 0, startTime = 0, totalTime = 0;
double start, end;
cout << "Program is now sorting using shell sort" <<endl;
startTime = time(NULL);
start = omp_get_wtime();// Start performance timer 1 run
shellSortParallel(arr, length);//Run the algorithm
end = omp_get_wtime();// End performance timer 1 run
endTime = time(NULL);
totalTime = endTime - startTime;
cout << "This is the time it took to run. " << totalTime << endl;// time in seconds
int stupid = 0;
cin >> stupid;
cout << "Program has completed all tasks!!" << endl;
return 0;
}
void shellSortParallel(int array[], int length)
{
int h;
int j = 0;
int temp = 0;
int i = 0;
for(h =length/2; h > 0; h = h/2)
{
#pragma omp parallel for shared( array, length, h, i) default(none)
for( i = 0; i < h; i++)
{
//int ID = omp_get_thread_num();
InsertSort(array, i, length, h);
}
}
}
void InsertSort(int arr[], int i, int length, int half)
{
//cout << ID << " ";
int temp = 0;
int j = 0;
for (int f = half + i; f < length; f = f + half)
{
j = f;
while(j > i && arr[j-half] > arr[j])
{
temp = arr[j];
arr[j] = arr[j-half];
arr[j-half] = temp;
j = j -half;
}
}
}
and here is the short version of the file that I'm going to read. Its a random number between 1 to 1million per line
2377763
88764877846
281327
60
625
86
646127818
14551
2177645
32033
1826761
555173
3415445377
32430
1101
any help would be much appreciate, thank you before
By if(fin>>data) you are not just testing, but retrieving data from stream. I suggest use ifs.good() for testing. Overall, you can write such a code instead
std::ifstream fin ("OUTPUT1.txt", std::ifstream::in);
char c = fin.get();
while (fin.good())
{
std::cout << c;
c = fin.get();
}
arr[n-1] = '\0'; is not correct because it's not an array of character so don't mind.
to correct it:
int data;
while(fin>>data)
{
arr[n] = data;
n++;
}
cout << "Displaying Array..." << endl << endl;
for(int i = 0; i < array_size; i++)
{
cout << arr[i];
}
why allocating such huge array of integers? use vector is a good thing:
vector<int> vec;
ifstream fin("OUTPUT1.txt");
int data;
while(fin >> data)
{
vec.push_back(data);
}
cout << "Displaying Array..." << endl << endl;
for(int i = 0; i < vec.size(); i++)
cout << vec[i] << endl;
fin.close();
88764877846 out band of an integer which causes the loop stop reading so you have to either get values as strings then convert into __int64 or __int128
to read values as strings:
string sLine;
int nLines = 0;
ifstream fin("OUTPUT1.txt");
// first read to get number of lines
while(getline(fin, sLine))
nLines++;
//create an array of strings
string* pstrValues = new string[nLines];
// set the get pointer to the beginning of file because the previous read moved it
fin.clear();
fin.seekg(0, ios::beg);
int i = 0;
while(getline(fin, sLine))
{
pstrValues[i] = sLine;
i++;
}
cout << "Displaying Array..." << endl << endl;
for( i = 0; i < nLines; i++)
cout << pstrValues[i] << endl;
fin.close();
now you have an array of strings convert it to int values but you must convert to __int64 because as I said there are values bigger than size of int (4bytes)

Multiple definition of main without any .cpp file in project folder c++

I'm trying to build a project which only contains one .cpp file. I'm pretty sure that there is no other files within the folder, but eclipse keep giving me:
multiple definition of `main'
Here is my code:
#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <vector>
using namespace std;
int main(){
string input;
vector<double> value;
int count = 0;
while(input != "#") {
cout << "Enter value " << count + 1 << "\n";
cin >> input;
if (input != "#") {
value[count] = atof(input.c_str());
}
count++;
}
cout << count;
double sum = 0;
for (int i = 0; i < count; i++) {
sum += value[i];
}
double ave = sum/count;
double dev = 0;
for (int i = 0; i < count; i++) {
dev += pow((value[i] - ave), 2);
}
dev = sqrt(dev / (count - 1));
cout << "\nThe average is " << ave << "\n";
cout << "The standard deviation is" << dev << "\n";
return 0;
}
Any help would be appreciated.
The comments are saying that your code is fine (I haven't tested it myself, though) so look around at your project directory, and see if there are any source files that shouldn't be there. If push comes to shove you can just copy/paste your code into a new project.

Confused about taking file name from command line and stuff to it C++

My problem is that I cant get the getting the filename from the command line from the user, then using that filename to write the median, mode, and average. Im new to c++ so any tips or code fix would be great, and if you guys see anything else wrong please let me know, this is what I have, Im 99% done with it its just this filewriting thats giving me problems. Thank you
#include <iostream>
#include <fsteam>
#include <string>
using namespace std;
double Median(int [], int);
double Average(int [], int);
double Mode(int [], int);
int main(int argc, char *argv[])
{
ofstream outFile;
string filename = argv[1];
outputFile.open(filename.c_str());
if(!outFile)
{
cerr << "Error with the file.";
}
else
{
continue;
}
int *array;
int array_size;
cout << "How many students were surveyed? " << endl;
cin >> array_size;
if(array_size < 1)
{
cout << "Number of students surveyed must be greater than 1." << endl;
return(1);
}
else
{
array = new int [array_size];
}
cout << "Enter the number of movies each studen saw." << endl;
for(int i = 0; i < array_size; i++)
{
cout << "Student " << i+1 << ": " << endl;
cin >> array[i];
}
for(int i = 0; i < array_size; i++)
{
for(int j = i+1; j < array_size-1; j++)
{
if(array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
double median = Median(array, array_size);
double average = Average(array, array_size);
double mode = Mode(array, array_size);
outFile << "Median: " << median << endl;
outFile << "Average: "<< average << endl;
outFile << "Mode: " << mode << endl;
return 0;
}
double Median(int arr[], int size)
{
double middle;
if(size%2 == 0)
middle = (arr[size/2] + arr[size/2-1])/2;
else
middle = arr[size/2];
return middle;
}
double Average(int arr[], int size)
{
double ave = 0;
for(int i = 0; i < size ; i++)
ave += arr[i];
ave = ave/size;
return ave;
}
double Mode(int arr[], int size)
{
int count, mode = 0;
for(int i = 0; i < size; i++)
{
count = 1;
while(arr[i] == arr[i+1])
{
count++;
i++;
}
if(count > mode)
mode = arr[i];
if(count > 1)
i--;
}
return mode;
}
You'll likely see something about this in the compiler, but I'll let you know anyways #include <fsteam> is <fstream>
I'm confused as to why you chose to put this
else
{
continue;
}
instead of nothing, since continue; just jumps to the end of the current iteration, which doesn't seem necessary here.
The rest of it seems fine. It's formatted to be easily read. If you have any errors post-testing, let me know.
EDIT: Sorry, I can't add comments yet, but in response to your comment, it's likely because of what I noted about <fstream> above. It's just a typo.
I tried it with following patch.
--- orig.cpp 2014-05-17 12:39:37.000000000 +0800
+++ new.cpp 2014-05-17 12:38:28.000000000 +0800
## -1,5 +1,5 ##
#include <iostream>
-#include <fsteam>
+#include <fstream>
#include <string>
using namespace std;
## -16,13 +16,13 ##
outputFile.open(filename.c_str());
- if(!outFile)
+ if(!outputFile)
{
cerr << "Error with the file.";
}
else
{
- continue;
+// continue;
}
## -64,9 +64,9 ##
double median = Median(array, array_size);
double average = Average(array, array_size);
double mode = Mode(array, array_size);
- outFile << "Median: " << median << endl;
- outFile << "Average: "<< average << endl;
- outFile << "Mode: " << mode << endl;
+ outputFile << "Median: " << median << endl;
+ outputFile << "Average: "<< average << endl;
+ outputFile << "Mode: " << mode << endl;
return 0;
}
I think that as following.
first, You type incorrectly with fsteam -> fstream.
second, you type incorrectly with outFile -> outputFile.
third, you must don't use continue without loop.
As result, I suggest you have more focus about typing error.
Better to check the count command line arguments.
int main(int argc, char *argv[])
{
if(argc <2 )
{
cout << "Specify out file name as command line argument";
return 0;
}
. . . . .
. . . . .
}
for more details,
http://www.cprogramming.com/tutorial/c/lesson14.html