I'm trying to get this code to only read from text file. And to output by counting of each number by stepping down the array and counting the values as you encounter them. Ti should ignore requirement read from keyboard or file.
#include <iostream>
#include <iomanip>
#include <ctype>
#include <stdlib>
#include <math>
#include <string>
#include <fstream>
#include <time>
//Bubble Sort - Descending Order
void bubbleSortDesc(int numbers[], int Max)
{
int i, j, temp;
for (i = 0; i <= (Max - 1); i++)
{
for (j = (Max - 1); j >= i+1; j--)
{
if (numbers[j] > numbers[j-1])
{
// Exchange the adjacent elements
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
}
}
int main()
{
int arr[1000],num,i,j,count=0,sum=0;
char choice;
cout<<endl<<"if you want to enter the datas to be stored in array by keyboard,press 1 "<<endl
<<"or press 2 if you want to store data in array from file"<<endl;
cin>>choice;
if(choice=='1')
{
cout<<endl<<"How many numbers do you want to enter to array"<<endl;
cin>>num;
cout<<endl<<"Enter integers to store in array"<<endl;
for(int i=0;i<num;i++)
cin>>arr[i];
bubbleSortDesc(arr,num);
for ( i = 0; i < num; i++)
{
for ( j = i + 1; j < num; j++)
{
if (arr[i] == arr[j])
{
num=num-1;
for (int k = j; k < num; k++)
arr[k] = arr[k + 1];
}
}
}
}
elseif(choice=='2')
{
char *inname = "source.txt";
ifstream indata; // indata is like cin
int num; // variable for input value
indata.open("source.txt"); // opens the file
if(!indata)
{ // file couldn't be opened
cerr << "Error: file could not be opened" << endl;
}
indata >> num;
while ( !indata.eof() )
{ // keep reading until end-of-file
cout << "The next number is " << num << endl;
++count;
indata >> num; // sets EOF flag if no value found
}
indata.close();
bubbleSortDesc(arr,count);
for ( i = 0; i < count; i++)
{
for ( j = i + 1; j < count; j++)
{
if (arr[i] == arr[j])
{
count=count-1;
for (int k = j; k < count; k++)
arr[k] = arr[k + 1];
}
}
}
}
if(choice=='1')
{
cout<<"Array with deleted elemnts"<<endl;
for(i=0;i<num;i++)
cout<<endl<<arr[i];
}
if(choice=='2')
{
for(i=0;i<count;i++)
cout<<endl<<arr[i];
}
return 1;
}
Line 75: You're missing something. That function should not continue if it couldn't open the text file.
When you say "only read from the text file", does that mean that you want to get rid of choice 1? Because in that case, all you'd need to do is delete some code, am I wrong?