I was looking for some help in sorting an Array. I have to do it this way, but I am getting some error messages I am not understanding such as:
[WARNING name lookup of 'index' changed .
matches this 'char* index[const char*, int] undr ISO standard rules
matches this index under old rules
invalid types 'int&[char()(const char*, int)] for array subscript
at global scope
I have some suspicion of what it is but a little lost of how to fix it.
The file I am opening is sentence that reads: Oliver was a Golden Retreiver whose fur was long and golden.
As you can tell I am a complete beginner so any tips will be greatly appreciated Thanks in advance!
#include <iostream>
#include <fstream>
using namespace std;
void swap_values(int& v1, int& v2);
int index_of_smallest(int list[],int start_index, int number_used);
void initialize(int list[]);
void Sort(int list[],int&num);
void characterCount(char ch, int list[]);
void readText(ifstream& intext, char& ch, int list[]);
void totalCount(int list[]);
int main()
{
int index,letterCount[26];
char ch;
ifstream inFile;
ofstream outFile;
cout<<"This is the text of the file:"<<endl;
outFile.open("C:/temp/Data_Chapter_7_8.txt");
if(!outFile)
{
cout<<"Cannot open file."<<endl;
}
inFile.open("C:/temp/Data_Chapter_7_8.txt");
if (!inFile)
{
cout << " Cannot open file." <<endl;
}
initialize(letterCount);
inFile.get(ch);
while (inFile.get(ch))
{
int index;
readText(inFile,ch,letterCount);
index++;
}
totalCount(letterCount);
inFile.close();
system("PAUSE");
return 0;
}
void initialize(int list[])
{
for(int x = 0;x<26;x++)
list[x] = 0;
}
void characterCount (char ch, int list[])
{
ch = tolower(ch);
if(static_cast<int>(ch)>=97&&(static_cast<int>(ch)<=122))
list[static_cast<int>(ch)-97]++;
}
void readText(ifstream& intext, char& ch, int list[])
{
if (ch != '.')
{
characterCount (ch,list);
}
}
void totalCount(int letterCount[])
{
for(int x=0;x<26;x++)
if(letterCount[x]>0)
cout<<static_cast<char>(x+97)<<" "<<letterCount[x]<<endl;
}
void Sort(int list[], int number_used)
{
int index_of_next_smallest;
for(int index= 0; index<number_used -1; index++)
index_of_next_smallest = index_of_smallest(list, index,number_used);
swap_values(list[index],list[index_of_next_smallest]);
}
}
int index_of_smallest(int list[], int start_index, int number_used);
{
int min = list[start_index];
index_of_min = start_index;
for (int index= start_index + 1; index < number_used; index++)
if (list[index]>min)
{
min = list[index];
index_of_min = index;
}
return index_of_min;
}
void swap_values(int& v1, int& v2)
{
int temp;
temp = v1;
v1 = v2;
v2 = temp;
}
Inside your Sort function, change
for(int index= 0; index<number_used -1; index++)
to
int index;
for(index = 0; index < number_used-1; index++)
because you need to access index after the loop ends.
Related
struct Student
{
char* name;
int balls;
};
void inputdata(Student **s, int *n)
{
int nn;
printf("%s\n", "Input amount of students");
scanf("%i", &nn);
Student* a = new Student[nn];
for (int i = 0; i < nn; ++i)
{
scanf("%s", &a[i].name);
scanf("%i", &a[i].balls);
}
n = &nn;
s = &a;
}
void print(Student **s, int n)
{
for (int i = 0; i < n; ++i)
{
printf("%s %i\n", s[i]->name, s[i]->balls);
}
}
int main(int argc, char const *argv[])
{
Student** s;
int *n;
inputdata(s, n);
print(s, *n);
return 0;
}
So how am I supposed to input data and print data on console screen.
I kinda input data, ok, unable to print it on my screen. Program ends. What am I supposed to fix here?
You should pass pointers to what should be modified in callee functions.
Callee functions should dereference pointers passed to modify what should be modified.
You have to allocate for strings before reading.
It is inconsistent that an array of Student in the function inputdata but an array of Student* is required in the function print.
You should limit the maximum length to read to the number of elements in the buffer minus one to prevent buffer overrun when you use %s. The "minus one" is for terminating null-character.
Fixed code:
#include <cstdio>
struct Student
{
char* name;
int balls;
};
void inputdata(Student **s, int *n)
{
int nn;
printf("%s\n", "Input amount of students");
scanf("%i", &nn);
Student* a = new Student[nn];
for (int i = 0; i < nn; ++i)
{
a[i].name = new char[4096];
scanf("%4095s", a[i].name);
scanf("%i", &a[i].balls);
}
*n = nn;
*s = a;
}
void print(Student *s, int n)
{
for (int i = 0; i < n; ++i)
{
printf("%s %i\n", s[i].name, s[i].balls);
}
}
int main(int argc, char const *argv[])
{
Student* s;
int n;
inputdata(&s, &n);
print(s, n);
return 0;
}
I have to make a program with a hash table that maps single random characters into the table. The program kind of works but sometimes it crashes, also it doesn't map every element. Some of them just won't get inside the table and there are always spare spaces in the table. I don't know what to do to solve these 2 problems. I used 3 versions of open adressing and each of them causes the same 2 problems. Sorry for my bad English. Thank you in advance.
Edited. Of course, I forgot about dynamic allocation. But the problem isn't solved.
#include <time.h>
#include <string>
#include <cstdlib>
using namespace std;
int Liniowo(int i, int proby, int rozmiar) // (open adressing, Linear probing)
{
if(i+proby<rozmiar)
return i+proby;
else
{
return -1;
}
}
int Kwadratowo(int i, int proby, int rozmiar) // (open adressing, Quadratic probing)
{
if (i+proby*proby<rozmiar)
return i+proby*proby;
else
{
return -1;
}
}
int Podwojnie(int i, int proby, int rozmiar, char klucz) // (open adressing, Double hashing)
{
if (i*(klucz*(701%klucz)-klucz%13)<rozmiar&&i*(klucz*(701%klucz)-klucz%13)>0)
return i*(klucz*(701%klucz)-klucz%13);
else
{
return -1;
}
}
int modularnie(char c,int rozmiar) // modular
{
return c%rozmiar;
}
void dodaj(char *tab,int max, char c) // add an element
{
int i=modularnie(c, max);
if (tab[i]== '\0')
tab[i]=c;
else
{
int u=0;
int h;
while (tab[i]!= '\0'&&h!=-1)
{
u++;
// h=Kwadratowo(i, u, max);
h=Podwojnie(i,u,max,c);
}
if (h!=-1)
tab[h]=c;
else
cout << "no niestety, nie udalo sie wstawic " <<endl; //"I couldn't map the element"
}
}
int wyszukaj(char *tab,int max, char c) // search an element
{
int i=modularnie(c, max);
int j=i;
if (tab[i]== '\0')
return -1;
while (tab[i]==c)
{
i=(i+1)%max;
if((i==j)||(tab[i]== '\0'))
return -1;
}
return i;
}
int usun(char *tab,int max, char c) // remove an element
{
int r,j,i=wyszukaj(tab,max,c);
j=i;
if (i==-1)
return -1;
tab[i]= '\0';
while (tab[(++i)%max]!= '\0')
{
i%=max;
r=modularnie(tab[i],max);
if (((i<r)&&(r<=j)) || ((r<=j)&&(j<i)) || ((j<i)&&(i<r)))
{
tab[j]=tab[i];
tab[i]= '\0';
j=i;
continue;
}
}
return 0;
}
int main()
{
srand( time( NULL ) );
int ile;
cout << "podaj wielkosc tablicy: "; //"Type the size of the table"
cin >> ile;
char* tab; // EDITED
tab=new char(ile);
for (int n=0; n<ile; n++)
{
tab[n]= '\0';
}
char e;
for (int i=0; i<ile; i++)
{
e='!'+rand()%127;
dodaj(tab, ile, e);
}
for(int j=0; j<ile; j++)
{
cout << j << ", " << tab[j] << endl;
}
return 0;
}
Okay, so my entire program is shown below. For some reason, when the partition function is called, it is throwing a stack overflow error. I have poured over the code and searched for help. You fine programmers are my last hope. Everything else works fine, or at least as well as it needs to. I'd appreciate it if you could look at the Quicksort and the partition functions for me and see if you can figure out where I messed up.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <time.h>
#include <stdio.h>
#include <dos.h>
using namespace std;
vector<int> DataIn(ifstream&);
void quickSort(int, int, vector<int>&, int);
int partition(vector<int>& list, int start, int end)
{
int pivot = list[start];
int index = start;
for (int i = start + 1; i < end; i++)
{
if (list[i] <= pivot)
{
swap(list[index], list[i]);
}
}
index++;
if (index != end)
{
swap(list[index], list[start]);
}
return index;
}
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int repeat = 0;
int fileCount = 1;
while (repeat == 0)
{
int loadFail = NULL;
cout << "\nWhat is the file name: ";
string fileName;
cin >> fileName;
ifstream fileIn(fileName);
do
{
if (fileIn.fail())
{
loadFail = 1;
cout << "\nUnable to open file. Please try again:";
cout << "\nWhat is the file name: ";
cin >> fileName;
ifstream fileIn(fileName);
if (fileIn.good())
{
loadFail = 0;
}
}
else
{
loadFail = 0;
}
} while (loadFail == 1);
vector<int> fileData;
fileData = DataIn(fileIn);
int fileLength = fileData.size();
void quickTime = quickSort(0, fileLength - 1, fileData, fileCount);
return 0;
};
vector<int> DataIn(ifstream& read)
{
vector<int> data;
int dataLine;
while (!read.eof())
{
read >> dataLine;
read.ignore();
data.push_back(dataLine);
}
return data;
}
void quickSort(int begin, int end, vector<int>& list, int fileNum)
{
int mid = 0;
if (end > begin)
{
mid = partition(list, begin, end);
quickSort(begin, mid, list, fileNum);
quickSort(mid + 1, end, list, fileNum);
}
return elapsed_time;
}
You have a few major issues in your posted code.
You are trying to return a value in void function (quickSort). Also I don't see where you declared that variable.
You are declaring a type void variable, which is wrong. A void function return void, that means that it doesn't return anything.
You have a missing bracket at the end of the main() function.
Your while loop will never stop, because repeat is always equal with 0.
In your quick sort function, in the first recursive call there should be mid-1
Your partitioning function logic is wrong
Also filenum variable is not used anywhere.
Here is a modified version of your code, that does work.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <time.h>
#include <stdio.h>
#include <dos.h>
using namespace std;
vector<int> DataIn(ifstream&);
void quickSort(int, int, vector<int>&);
int partition(vector<int>& arr, int left, int right)
{
int pivot = arr[left];
while (left != right)
{
if (arr[left] > arr[right])
{
swap(arr[left], arr[right]);
}
if (pivot == arr[left])
right--;
else
left++;
}
return left;
}
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int repeat = 0;
int fileCount = 1;
int loadFail = NULL;
cout << "\nWhat is the file name: ";
string fileName;
cin >> fileName;
ifstream fileIn(fileName);
do
{
if (fileIn.fail())
{
loadFail = 1;
cout << "\nUnable to open file. Please try again:";
cout << "\nWhat is the file name: ";
cin >> fileName;
ifstream fileIn(fileName);
if (fileIn.good())
{
loadFail = 0;
}
}
else
{
loadFail = 0;
}
} while (loadFail == 1);
vector<int> fileData;
fileData = DataIn(fileIn);
int fileLength = fileData.size();
quickSort(0, fileLength - 1, fileData);
return 0;
}
vector<int> DataIn(ifstream& read)
{
vector<int> data;
int dataLine;
while (!read.eof())
{
read >> dataLine;
read.ignore();
data.push_back(dataLine);
}
return data;
}
void quickSort(int begin, int end, vector<int>& list)
{
int mid = 0;
if (end > begin)
{
mid = partition(list, begin, end);
quickSort(begin, mid-1, list);
quickSort(mid + 1, end, list);
}
}
This question already has answers here:
Calling a function in main
(4 answers)
Closed 4 years ago.
Okay, I think I fixed most of this, but it doesn't like me passing the constants I think. Any help would be greatly appreciated, thank you.
also, with the !inputFile part, I'm not sure how to pull off a return (EXIT_FAILURE) like my teacher suggested..
Also, as to your suggestion with only using one part of the array, would that still allow me to use the whole thing in the function?
The program is supposed to take a file like this:
ex:
NOT 11010001
and it's supposed to read the command as a string, read the binary in as an array, then perform the command on the binary.
The code here is only main function, just don't want to send a wall of it all at once, if this looks okay, then I will happily add the rest. Also, the void Operate () function pretty much calls all of the other functions in one way or another... I'm not sure if that's what's causing it or what. The print table only cout's a table to put all of the info on.
and they headers are wonky for me on here, so just assume those are right.
/* ========================================================================== */
/* Prototypes */
int Power (int, int);
int ReadFile (ifstream inputFile);
void Operate (const int, ifstream&, string, int, int, int);
void CommandNot (const int, int, int);
void CommandAnd (const int, int, int, int);
void CommandOr (const int, int, int, int);
int CommandConvert (const int, int, int);
void CommandLshift (const int, int, int, int);
void PrintTable ();
void PrintOperand (const int &, int);
int main ()
{
//Constants
const int BIT_SIZE = 8;
//Variables
string fileName = "binaryData.txt";
int operandOne [BIT_SIZE];
int operandTwo [BIT_SIZE];
int operandResult [BIT_SIZE];
ifstream inputFile;
PrintTable ();
Operate (BIT_SIZE, inputFile, fileName, operandOne[BIT_SIZE], operandTwo[BIT_SIZE], operandResult[BIT_SIZE]);
return 0;
}
void PrintTable ()
{
cout << "=================================================" << endl;
cout << "= Eight Bit Binary Number Manipulator =" << endl;
cout << "=================================================" << endl << endl;
cout << setw(14) << "COMMAND" << "Operand #1" << "Operand #2" << "Shift" << "Result" << endl;
cout << "----------------------------------------------------------------------" << endl;
}
void Operate (const int BIT_SIZE, ifstream& inputFile, string fileName, int operandOne[], int operandTwo[], int operandResult[])
{
//Variables
int count, shift;
char myChar;
string command;
const int SIZE = BIT_SIZE; //rename constant
inputFile.open (fileName);
if ( !inputFile ) //Check if file opened sucessfully
{
cout << "Error: Data file could not be opened" << endl;
}
while (inputFile) //Read file, and apply commands
{
inputFile >> command;
cout << command << endl;
for ( count = 0; count < SIZE; count++ )
{
inputFile >> myChar;
operandOne[count] = myChar - '0';
}
if (command == "NOT")
{
CommandNot (BIT_SIZE, operandOne[BIT_SIZE], operandResult[BIT_SIZE]);
PrintOperand (BIT_SIZE, operandResult[BIT_SIZE]);
}
else if (command == "AND")
{
count = 0;
for ( count = 0; count < SIZE; count++ )
{
inputFile >> myChar;
operandTwo[count] = myChar - '0';
}
CommandAnd (BIT_SIZE, operandOne[BIT_SIZE], operandTwo[BIT_SIZE], operandResult[BIT_SIZE]);
PrintOperand (BIT_SIZE, operandResult[BIT_SIZE]);
}
else if (command == "OR")
{
count = 0;
for ( count = 0; count < SIZE; count++ )
{
inputFile >> myChar;
operandTwo[count] = myChar - '0';
}
CommandOr (BIT_SIZE, operandOne[BIT_SIZE], operandTwo[BIT_SIZE], operandResult[BIT_SIZE]);
PrintOperand (BIT_SIZE, operandResult[BIT_SIZE]);
}
else if (command == "CONVERT")
{
CommandConvert (BIT_SIZE, operandOne[BIT_SIZE], operandResult[BIT_SIZE]);
PrintOperand (BIT_SIZE, operandResult[BIT_SIZE]);
}
else if (command == "LSHIFT")
{
inputFile >> shift;
CommandLshift (BIT_SIZE, operandOne[BIT_SIZE], operandResult[BIT_SIZE], shift);
PrintOperand (BIT_SIZE, operandResult[BIT_SIZE]);
}
else
{
command = "INVALID";
PrintOperand (BIT_SIZE, operandOne[BIT_SIZE]);
cout << "--- ERROR! Invalid Command ---";
}
}
inputFile.clear();
inputFile.close();
return ;
}
void CommandNot (const int BIT_SIZE, int operandOne[], int operandResult[])
{
int count;
const int SIZE = BIT_SIZE;
for ( count = 0; count < SIZE; count++ )
{
if (operandOne[count] == 0)
{
operandResult[count] = 1;
}
else
{
operandResult[count] = 0;
}
}
}
void CommandAnd (const int BIT_SIZE, int operandOne[], int operandTwo[], int operandResult[])
{
int count;
const int SIZE = BIT_SIZE;
for ( count = 0; count < SIZE; count++ )
{
if ((operandOne[count] == 1) && (operandTwo[count] == 1))
{
operandResult[count] = 1;
}
else
{
operandResult[count] = 0;
}
}
}
void CommandOr (const int BIT_SIZE, int operandOne[], int operandTwo[], int operandResult[])
{
int count;
const int SIZE = BIT_SIZE;
for ( count = 0; count < SIZE; count++ )
{
if ((operandOne[count] == 0) && (operandTwo[count] == 0))
{
operandResult[count] = 0;
}
else
{
operandResult[count] = 1;
}
}
}
int CommandConvert (const int BIT_SIZE, int operandOne[])
{
int count;
const int SIZE = BIT_SIZE;
int baseTenResult = 0;
int place;
for ( count = 0; count < SIZE; count++ )
{
place = SIZE - (count + 1);
if (operandOne[count] == 1)
{
baseTenResult = baseTenResult + Power (2, place);
}
else
{
continue;
}
}
return baseTenResult;
}
void CommandLshift (const int BIT_SIZE, int operandOne[], int operandResult[], int shift)
{
int count;
const int SIZE = BIT_SIZE;
int shiftStart = SIZE - shift;
for ( count = 0; count < SIZE-shift; count++ )
{
operandResult[count] = operandOne[count + shift];
}
for ( count = SIZE - shift; count < SIZE; count++ )
{
operandResult[count] = 0;
}
}
int Power (int base, int power)
{
int count;
int result = 1;
for ( count = 0; count < power; count++ )
{
result = result * base;
}
return result;
}
void PrintOperand (const int BIT_SIZE, int operandResult[])
{
int count;
const int SIZE = BIT_SIZE;
for ( count = 0; count < SIZE; count++ )
{
cout << operandResult[count];
}
}
You need to call the functions from main. You can't do this by sort-of redeclaring them:
void PrintTable();
void Operate (const int BIT_SIZE, ifstream& inputFile, string fileName, int operandOne[], int operandTwo[], int operandResult[]);
Instead, you need to call them:
PrintTable();
Operate(BITSIZE,inputFile,fileName,operandOne,operandTwo,operandResult);
Note, however that there is another problem: Operate requires three integer arguments at the end, but you seem to try to use integer arrays as arguments. You'll need to select one element of each array and submit only that as argument.
(EDIT) A few things have changed in your question, and I don't understand enough to tell what the best overall structure for your data and functions should be, but if you are dealing with integer arrays and you'd like to pass an entire array to a function, you can do it in this way (I've simplified it to a function that takes only one array of integers. Of course you can have more than one function argument):
#include <iostream>
const int SIZE = 3;
/* This is a simpified version of 'operate'. It
takes one argument, which is an array of integers. */
void operate(int a[])
{
/* The only thing I do is to iterate through
all elements of the array and print them. */
int i = 0;
while (i < SIZE) {
std::cout << a[i] << std::endl;
++i;
}
/* IMPORTANT: The length of the array is defined by a
global constant SIZE. Alternatively, you can pass
along the size of the array as a separate argument
to the function. */
}
int main()
{
/* Main program. Here is our array: */
int my_array[SIZE] = { 1,2,3 };
/* And here we call our function: */
operate(my_array);
return 0;
}
However, all of this is a bit complicated and not really as conventient as you could have it in C++ (as opposed to C). In all likelihood, you'll be much better of not using arrays at all, and replacing them with std::vector. Best check on cppreference for examples of how to use it (also click on some of the member functions, such as the constructor and push_back to get specific code examples.)
I have been working on an assignment to take a sentence from a file and output the number of character occurrences in the file and sort it from highest to lowest. The sentence in the file is "Oliver was a Golden Retreiver whose fur was long and golden.". The period in the file serves as a sentinel value. I am a little lost as to where to put the Sort function. The program compiles though it only shows a blank screen. Could anyone give me some tips on how to go about debugging these problems?
#include <iostream>
#include <fstream>
using namespace std;
void swap_values(int& v1, int& v2);
int index_of_smallest(int list[],int start_index, int number_used);
void initialize(int list[]);
void Sort(int list[],int&number_used);
void characterCount(char ch, int list[]);
void readText(ifstream& intext, char& ch, int list[]);
void totalCount(int list[]);
int main()
{
int letterCount[26], number_used;
char ch;
ifstream inFile;
inFile.open("Data_Chapter_7_8.txt");
if (!inFile)
{
cout << " Cannot open file." <<endl;
}
initialize(letterCount);
while (inFile.get(ch))
{
readText(inFile,ch,letterCount);
}
totalCount(letterCount);
inFile.close();
system("PAUSE");
return 0;
}
void initialize(int list[])
{
for(int x = 0;x<26;x++)
list[x] = 0;
}
void characterCount (char ch, int list[])
{
ch = tolower(ch);
if(static_cast<int>(ch)>=97&&(static_cast<int>(ch)<=122))
list[static_cast<int>(ch)-97]++;
}
void readText(ifstream& intext, char& ch, int list[])
{
if (ch != '.')
{
characterCount (ch,list);
}
}
void totalCount(int letterCount[])
{
for(int x=0;x<26;x++)
if(letterCount[x]>0)
cout<<static_cast<char>(x+97)<<" "<<letterCount[x]<<endl;
}
void Sort(int list[], int number_used)
{
int index_of_next_smallest;
int index;
for(index= 0; index<number_used -1; index++)
index_of_next_smallest = index_of_smallest(list, index,number_used);
swap_values(list[index],list[index_of_next_smallest]);
}
int index_of_smallest(int list[], int start_index, int number_used)
{
int index_of_min;
int min = list[start_index];
index_of_min = start_index;
for (int index= start_index + 1; index < number_used; index++)
if (list[index]>min)
{
min = list[index];
index_of_min = index;
}
return index_of_min;
}
void swap_values(int& v1, int& v2)
{
int temp;
temp = v1;
v1 = v2;
v2 = temp;
}