I was wondering is someone could help me out of sorting this array, I am i little lost on how to exactly implement it in this project. Because it is HW do not reveal the whole answer, but push me towards the right direction. The project is as follows:
Write a program that will read a line of text and output a list of all the letters that occur in the text together with the number of times each letter occurs in the line. End the line with a period that serves as a sentinel value. The letters should be used in the following order: highest to lowest.Assume that the input used all lowercase letters.
A couple questions.
1. Am I going along the right way in sorting the array?
2. Before putting the sorting array into my code, when the code compiles it comes up with a blank screen. Any ways to fix this?
Apologies if this is written poorly, and thanks in advance for the help!
inlcude <iostream>
#inlcude <fstream>
using namespace std;
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;
infile.open("C:/temp/Data_Chapter_7_8.txt");
if (!inFile)
{
cout << " Cannot open file." <<endl;
}
initialize(letterCount);
infile.get(ch);
while (inFile)
{
int index;
readText(inFile,ch,letterCount)
index++;
inFile.get(ch);
}
totalCount(index, letterCount);
inFile.close();
system("PAUSE");
return 0;
}
//initializes array letterCount to 0
void initialize(int list[])
{
for(int x = 0;x<26;x++)
list[x] = 0
}
//increments the letter count. Makes sure counting letters.
void characterCount (char ch, int list[])
{
int index;
ch = tolower(ch);
if(static_cast<int>(ch)>=97&&(static_cast<int>(ch)<=122))
letterCount[static_cast<int>(ch)-97]++;
}
void readText(ifstream& intext, char& ch, int list[])
{
while (ch != '.')
{
characterCount (ch,list);
intext.get(ch);
}
}
//displays data
void totalCount(int list[])
{
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& num)
{
int i,j,flag = 1;
int temp;
int numLength = num.length();
for (i=1;(i<=numLength)&&flag; i++)
{
flag = 0;
for (j=o; j<(numLength-1);j++0
{
if(num[j+1]>num[j])
{
temp = num[j];
num[j] = num[j+1];
num[j+1]=temp;
flag = 1;
}
}
}
return;
}
Instead of using messy bubble sorts and other fun stuff, we can simply keep track of the number of occurrences of each letter, since there are only 26 possibilities. This should result in a bit cleaner (and much faster) code:
int numOccur[26];
...
for (int i = 0; i < numCh; i ++)
numOccur[letters[i] - 'a'] ++;
for (i = 25; i >= 0; i --)
if (i > 0)
cout<<static_cast<char>(i+97)<<" "<<numOccur[i]<<endl;
Of course, you should replace the for loop with the appropriate file-reading loop.
Just a few comments.
I don't see any good reason for most of the casting here.
Use isalpha, isupper or islower to check for letters, and tolower or toupper to covnert them (Note: using these functions is one of the few justifications for casting).
Probably easiest to initialize your lettercount array with `int lettercount[26] ={0};
Unless you're absolutely required to write your own sort routine, just use std::sort.
It's usually easiest to open a file as you define your ifstream:
std::ifstream infile("whatever");
Don't use while (infile). It's pretty much a guaranteed bug. Do a read, and check whether it succeeded, like: while (infile.get(ch)) ...
Related
I am writing a C++ program for homework, and it needs to count the characters in a char arr[n] string. However, my counter keeps returning the wrong values. I have looked through other answers to similar questions, however, they are not specific to C++ and none of the answers explain the value I am getting.
#include<iostream>
using namespace std;
#include<string.h>
#include <stdlib.h>
class Counter
{
public:
char word[20];
int totChar{ 0 };
void setWord(char word)
{
this->word[20] = word;
}
void setCount(int totChar)
{
this->totChar = totChar;
}
int getLength()
{
return totChar;
}
void charCount()
{
int n = 0;
for (int i = 0; word[i] != '\0'; i++) {
if (word[i] != '\0')
{
n++;
}
}
setCount(n);
}
};
int main()
{
char text[20];
cout << "Enter the string:" << endl;
cin >> text;
Logic input;
input.setWord(text[20]);
input.charCount();
// input.resetWord();
cout << input.getLength();
}
So it seems you haven't figured out how arrays and C strings work in C++ yet.
void setWord(const char* word)
{
strcpy(this->word, word);
}
and
Logic input;
input.setWord(text);
Your code is a bit weird, I guess you are just experimenting, but I think those two changes should make it work.
This code is for printing left recursion alternatives in a production.But when printing alternatives at last garbage values are being added.Why am i getting such error?
how to resolve such problem?in the image the output is displayed.but that is the wrong output
#include<iostream>
#include<cstring>
using namespace std;
class production
{
private:
char lhs;
char rhs[10][10],lr[10][10];
int noa;
public:
production()
{
noa=0;
}
void makeprod(char *str)
{
lhs=str[0];
char r[20];
strcpy(r,str+3);
int j=0;
for(int i=0;r[i]!='\0';i++)
{
if(r[i]!='/')
rhs[noa][j++]=r[i];
else
{
rhs[noa++][j]='\0';
j=0;
}
}
noa++;
}
void checkLR()
{
int ct=0,m=0;
for(int i=0;i<noa;i++)
if(lhs==rhs[i][0])
{
strcpy(lr[m],rhs[i]);
m++;
ct++;
}
if(ct>0)
{
for(int k=0;k<ct;k++)
cout<<"Left recursion at "<<lr[k]<<"\n";
}
else
cout<<"no\n";
}
void printprod()
{
cout<<"LHS = "<<lhs<<"\n";
cout<<"RHS = ";
for(int i=0;i<noa;i++)
cout<<rhs[i]<<" ";
}
};
int main()
{
production p;
char str[20];
cout<<"enter a production\n";
cin>>str;
p.makeprod(str);
p.printprod();
p.checkLR();
return 0;
}
In makeprod you're checking your input string for / to add the termination character to your rhs-array, and thus your input string has to end with the / sign. You have several choices :
either initialize your arrays with 0, so the rhs-array is always null-terminated (independently from your question : It's always good practice to initialize your variables)
add a null-termination sign (0) to rhs when the end of your input string is reached
edit: Just place a memset(rhs, 0, sizeof(rhs)*sizeof(char)); (the same for lr) in your constructor and the output should be fine. This will initialize your arrays with zeroes and thus the string is null-terminated.
But you really should add some overflow checking.
You are propably incrementing noa one time too much in makeprod().
That makes the for loop in printprod() access rhs 1 element after its end.
I've been trying to bend my head around this problem for a week now, but I can't seem to find anything online and I've given up on trying to solve it on my own.
My assignment is to write a program which will read names from a file and accept new entries from the user, then sort the entires and write them out to the file. The only crux about this is that I have to sort them in a function and use pointers to do so. This code is supposed to be written in C++ aswell, using character arrays.
The code I have right now looks like this. This is a working version, the only problem is that I don't use neither pointers or a function to sort the names.
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<cstring>
bool sorted;
using namespace std;
int main()
{
int i = 0;
int numNames = 0;
ifstream ifs;
ifs.open("namn.txt");
char c[20][20];
if(ifs.is_open())
{
while(!ifs.eof())
{
ifs >> c[i];
i++;
}
}
cout<<"How many names do you want to enter?"<<endl;
cin>>numNames;
for(int l = i-1; l<numNames+i-1; l++)
{
system("cls");
cout<<"Enter a name: ";
cin>>c[l];
}
while(sorted == false)
{
for(int j = 0; j<numNames+i-1; j++)
{
for(int k = j; k<numNames+i-1; k++)
{
if(c[j][0] > c[k][0])
{
char snorre[20];
strcpy(snorre,c[j]);
strcpy(c[j],c[k]);
strcpy(c[k],snorre);
}
else if(c[j][0] == c[k][0])
{
if(c[j][1] > c[k][1])
{
char snorre[20];
strcpy(snorre,c[j]);
strcpy(c[j],c[k]);
strcpy(c[k],snorre);
}
}
}
}
cout<<endl<<endl<<endl;
ofstream ofs;
ofs.open("namn.txt");
for(int o = 0; o<numNames+i-1; o++)
{
cout<<c[o]<<" ";
ofs<<c[o]<<endl;
}
ofs.close();
system("pause");
sorted = true;
}
}
So hopefully someone could help me out with this problem, thanks in advance! :)
To get your code to use pointers and functions, you can do this- you should change your code and make it use the following:
First, Get each name from the file to an std::string, using getline(ifstream_object, std::string_object), for reference see here.
Convert each one to a const char * (also shown in that example), using .c_str().
Do the following to each of the new names entered.
Store all names entered in this array pointers: char *names[20];, like this: names[i] = name;
Next, Create a function such as follows:
int location_of_bigger_string(const char* s1, const char* s2)
{
// Returns 1 if s1 should be before s2 and 2 otherwise
// This way, you use functions and pointers together.
// Use strcmp(s1,s2) here to determine returning value
}
strcmp(char*, char*) - read about it here.
Finally, to sort all the strings, use qsort or this example.
Here's the complete code,
Note that the compare function gets pointers to the elements, here the elements are pointers themselves, so what's passed to "compare" function is of type "char **"
{
#include "stdafx.h"
#include<iostream>
//retruns +1 if str1 > str2 alphabetically
int compare(const void * a, const void * b )
{
const char * str1 = *((const char **)a);
const char * str2 = *((const char **)b);
int i;
for ( i = 0 ; str1[i] && str2[i] ; i++ )
{
if ( str1[i] > str2[i] )
{
return +1;
}
else if ( str1[i] < str2[i] )
{
return -1;
}
}
//one or both strings have ended
if (str1[i]) //str1 is longer
return +1;
else if (str2[i]) //str2 is longer
return -1;
else
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
char * names[]={"Zebra","Kousha","Koosha","Kou","Koush","Test"};
qsort( names, 6, sizeof(char *), compare );
return 0;
}
}
I can't figure out how to do this.
The question: Implement the function
int count_matches(const string arr[], int size, string query);
Return the number of strings in the array that are equal to query or
-1 if size if less than 0.
My answer:
#include <iostream>
#include <cmath>
#include<string>
using namespace std;
int count_matches(const string arr[], int size, string query){
int i = 0;
int numMatches;
for (;i<size;i++) {
if (string[i] == (string[i]+1)){
numMatches++;
}
}
return numMatches;
}
int main(){
string selection;
const string array[4]={"dog", "cat", "dog", "dog"};
cout<<"which animal do you want?"<<endl;
cin>> selection;
cout<< "there are " << count_matches(array, 4, selection)<< " matches"<<endl;
return 0;
}
What is wrong?
int count_matches(const string arr[], int size, string query){
int numMatches(0);
for (int i=0; i<size; ++i)
{
if (arr[i] == string)
{
++numMatches;
}
}
return numMatches;
}
This should be a solution to your problem but you will never learn anything from gaining the answer this way. I'd advise reading this tutorial on arrays and loops to better understand how to tackle the problem next time.
Once you get your code to compile, you need to look carefully at this block:
if (string[i] == (string[i]+1)) {
numMatches++;
}
What do you actually want to compare here? string is a type. Take another look at the arguments that you pass into the function and that should make it clear.
Then, once you have a match, you increment numMatches. But what value does this have to start with? What value should it have to start with?
Note that std::count() does exactly what your count_matches() function should do:
std::count(array, array + 4, selection)
This will probably not statisfy whomever marks your homework, but it is worth playing with and learning if you want to advance your C++ skills.
Good luck!
Can someone help me with this: This is a program to find all the permutations of a string of any length. Need a non-recursive form of the same. ( a C language implementation is preferred)
using namespace std;
string swtch(string topermute, int x, int y)
{
string newstring = topermute;
newstring[x] = newstring[y];
newstring[y] = topermute[x]; //avoids temp variable
return newstring;
}
void permute(string topermute, int place)
{
if(place == topermute.length() - 1)
{
cout<<topermute<<endl;
}
for(int nextchar = place; nextchar < topermute.length(); nextchar++)
{
permute(swtch(topermute, place, nextchar),place+1);
}
}
int main(int argc, char* argv[])
{
if(argc!=2)
{
cout<<"Proper input is 'permute string'";
return 1;
}
permute(argv[1], 0);
return 0;
}
Another approach would be to allocate an array of n! char arrays and fill them in the same way that you would by hand.
If the string is "abcd", put all of the "a" chars in position 0 for the first n-1! arrays, in position 1 for the next n-1! arrays, etc. Then put all of the "b" chars in position 1 for the first n-2! arrays, etc, all of the "c" chars in position 2 for the first n-3! arrays, etc, and all of the "d" chars in position 3 for the first n-4! arrays, etc, using modulo n arithmetic in each case to move from position 3 to position 0 as you are filling out the arrays.
No swapping is necessary and you know early on if you have enough memory to store the results or not.
A stack based non-recursive equivalent of your code:
#include <iostream>
#include <string>
struct State
{
State (std::string topermute_, int place_, int nextchar_, State* next_ = 0)
: topermute (topermute_)
, place (place_)
, nextchar (nextchar_)
, next (next_)
{
}
std::string topermute;
int place;
int nextchar;
State* next;
};
std::string swtch (std::string topermute, int x, int y)
{
std::string newstring = topermute;
newstring[x] = newstring[y];
newstring[y] = topermute[x]; //avoids temp variable
return newstring;
}
void permute (std::string topermute, int place = 0)
{
// Linked list stack.
State* top = new State (topermute, place, place);
while (top != 0)
{
State* pop = top;
top = pop->next;
if (pop->place == pop->topermute.length () - 1)
{
std::cout << pop->topermute << std::endl;
}
for (int i = pop->place; i < pop->topermute.length (); ++i)
{
top = new State (swtch (pop->topermute, pop->place, i), pop->place + 1, i, top);
}
delete pop;
}
}
int main (int argc, char* argv[])
{
if (argc!=2)
{
std::cout<<"Proper input is 'permute string'";
return 1;
}
else
{
permute (argv[1]);
}
return 0;
}
I've tried to make it C-like and avoided c++ STL containers and member functions (used a constructor for simplicity though).
Note, the permutations are generated in reverse order to the original.
I should add that using a stack in this way is just simulating recursion.
First one advice - don't pass std:string arguments by value. Use const references
string swtch(const string& topermute, int x, int y)
void permute(const string & topermute, int place)
It will save you a lot of unnecessary copying.
As for C++ solution, you have functions std::next_permutation and std::prev_permutation in algorithm header. So you can write:
int main(int argc, char* argv[])
{
if(argc!=2)
{
cout<<"Proper input is 'permute string'" << endl;
return 1;
}
std::string copy = argv[1];
// program argument and lexically greater permutations
do
{
std::cout << copy << endl;
}
while (std::next_permutation(copy.begin(), copy.end());
// lexically smaller permutations of argument
std::string copy = argv[1];
while (std::prev_permutation(copy.begin(), copy.end())
{
std::cout << copy << endl;
}
return 0;
}
As for C solution, you have to change variables types from std::string to char * (ugh, and you have to manage memory properly). I think similar approach - writing functions
int next_permutation(char * begin, char * end);
int prev_permutation(char * begin, char * end);
with same semantics as STL functions - will do. You can find source code for std::next_permutation with explanation here. I hope you can manage to write a similar code that works on char * (BTW std::next_permutation can work with char * with no problems, but you wanted C solution) as I am to lazy to do it by myself :-)
Have you tried using the STL? There is an algorithm called next_permutation which given a range will return true on each subsequent call until all permutations have been encountered. Works not only on strings but on any "sequence" type.
http://www.sgi.com/tech/stl/next_permutation.html
This solves the problem without recursion. The only issue is that it will generate duplicate output in the case where a character is repeated in the string.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
int factorial(int n)
{
int fact=1;
for(int i=2;i<=n;i++)
fact*=i;
return fact;
}
char *str;
void swap(int i,int j)
{
char temp=str[i];
str[i]=str[j];
str[j]=temp;
}
void main()
{
clrscr();
int len,fact,count=1;
cout<<"Enter the string:";
gets(str);
len=strlen(str);
fact=factorial(len);
for(int i=0;i<fact;i++)
{
int j=i%(len-1);
swap(j,j+1);
cout<<"\n"<<count++<<". ";
for(int k=0;k<len;k++)
cout<<str[k];
}
getch();
}
#include <iostream>
#include <string>
using namespace std;
void permuteString(string& str, int i)
{
for (int j = 0; j < i; j++) {
swap(str[j], str[j+1]);
cout << str << endl;
}
}
int factorial(int n)
{
if (n != 1) return n*factorial(n-1);
}
int main()
{
string str;
cout << "Enter string: ";
cin >> str;
cout << str.length() << endl;
int fact = factorial(str.length());
int a = fact/((str.length()-1));
for (int i = 0; i < a; i++) {
permuteString(str, (str.length()-1));
}
}