Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
When I input a string that starts with the letter 'a' the program fails to check for that letter and excludes it. If i input a string that has an 'a' just not first in string, it checks out.
Here is the complete problem:
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 or delimiting character.
The letters should be listed in the following order: the most frequently occurring letter, the next most frequently occurring letter, and so forth.
Use two arrays, one to hold letters and one to hold integers. You may assume that the input uses all lowercase letters. For example, the input do be go bo. Should produce output similar to the following:
Letter Numbers of Occurrence
o 3
b 2
d 1
e 1
Note: you can modify the implementation of the selection sort algorithm in the book to sort the array in descending order. You can use either string type or c-string type in your program.
Code:
#include<iostream>
#include<string>
using namespace std;
void sort(char letters[],int letter_count[])
{
for(int i=0; i<26; i++)
{
int max = i;
for(int j=i; j<26; j++)
{
if(letter_count[j] > letter_count[max]) max = j;
}
int temp = letter_count[i];
letter_count[i] = letter_count[max];
letter_count[max] = temp;
char local = letters[i];
letters[i] = letters[max];
letters[max] = letters[i];
}
}
int main()
{
string str;
char letters[26];
int letter_count[26] = {0 };
cout <<"Enter a line of text :";
getline(cin,str);
for(int i=0; i<str.length(); i++)
letter_count[str[i]-'a']++;
for(int i=0; i<26; i++)
letters[i] = static_cast<char> ('a'+i);
sort(letters, letter_count);
cout <<"Letter Numbers of Occurrence" << endl;
for(int i=0; i<26; i++) {
if(letter_count[i]!=0)
cout << letters[i] << " " << letter_count[i]<<endl;
}
return 0;
}
Problem found on line 20, where you try to swap letters[i] with letters[max]. That line should be
letters[max] = local;
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
New to programming, I have tried just about everything to get my program to run, but cannot figure it out. This is for my Into to programming course, so I'll be posting the instructions for it as well for context purposes.
I know for a fact that my program is running properly up until the closing bracket in line 62. The primary issue that im having is right after that, where I call the function sharedLetters. For context, I have attempted multiple ways of trying to fix the function definition, so at this point its a little jumbled, but it was wrong to begin with, so there's that. As for the remainder of the code, im not entirely sure if its written correct or not, as I cant get beyond the called function.
Assignment Instructions
For this assignment, you will write a program that forms the basis of a crossword puzzle generator. In order to create a crossword puzzle you need to identify letters that are common to one or more words. This program helps you generate crossword puzzles by identifying letters that are common to several words and storing them in an intermediate data structure.
Using intermediate data structures is one way to simplify your coding. You create a data structure that organizes your input so the final output is easier to create. Your CrosswordGenerator program will open a file containing a list of words. To prepare for crossword puzzle generation your code should implement the following pseudo code:
Open a file named wordlist.txt
Determine the number of words (N) in the file.
Create an array of that size called wordArray[];
Read all the words from the file into an array called wordArray[N].
Sort the array of words by length in descending order
Start at the beginning of the array (the longest word) and examine the word
Find all other words in the array that can intersect the current word
Two words can intersect if they share a letter.
Write a function called String sharedLetters(String S1, String S2).
Implement sharedLetters(S1,S2) that will return a string containing letters shared by the two parameter strings S1 and S2.
If no letters are shared between S1 and S2 sharedLetters() should return the empty string "".
sharedLetters(S1,S2) should ignore case; capital and lower case letters are considered equal.
Create a two dimensional array of Strings wordsIntersect[N][N] where each dimension N is the size of wordArray.
Iterate over wordArray comparing distinct words. Do not compare a word to itself.
If wordArray[i] shares any letters with wordArray[j] place the result of sharedLetters(wordArray[i],wordArray[j]) into wordsIntersect[i][j].
Non-alphabetic characters should be ignored.
Upper and lower case letters should be equivalent. Your program should not treat them as distinct tokens.
The order of shared letters is not a consideration for this program.
Write the contents of the wordsIntersect array to a Comma Separated Values (CSV) text file named wordsIntersect.csv in row-major form: row,col,value. In the example below, there is an entry in wordsIntersect[12][33] which contains the string "tci". There would also be a line in wordsIntersect.csv that contains 12,33,tci -- there are no quotes around the letters and the line ends after the letter 'i'. Given that wordsIntersect[12][78] will contains "" there would be a line in the file containing: 12,78, where there is an end of line after the last comma.
N.B.
Example of what sharedLetters() output.
SharedLetters(transaction,dictum) returns "tci"
SharedLetters(Transaction,kudzu) returns ""
If "transaction" is stored in wordArray[12] and "dictum" is stored in wordArray[33] then wordsIntersect[12][33] will contain "tci".
If "kudzu" is stored in wordArray[78] then wordsIntersect[12][78] will contain "".
My actual code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
using std::string;
//calling function that will record shared letters between words, to be called later
string sharedLetters(string S1[], string S2[]);
int main ()
{
//variables for indexes used in arrays
int i, compareIndex, count = 0;
//declaring array and its total size based on total words in file
const int N = 644;
string wordArray[N];
//declaring a 2-D array wordsIntersect, setting size of both dimensions to 'N'
string wordsIntersect[644][644];
//declaring file
ifstream file;
//opening file
file.open("wordlist.txt");
cout << "Reading data from the file." << endl;
while (count < N)
{
file >> wordArray[count];
count++;
}
//closing the file
cout << "Closing the wordlist.txt file now." << endl;
file.close();
//sort the array of strings in descending order using SelectionSort
//going through array of strings, wordArray[]
for (int i = 0; i < N; i++)
{
//creating a nested for loop to compare indexes
for (int compareIndex = i + 1; compareIndex < N; compareIndex++)
{
//compare the words at both indexes to determine which one is longer
if (wordArray[i].length() < wordArray[compareIndex].length())
{
//if true, swap the elements using selectionSort
string longerWord = wordArray[compareIndex];
//swap indexes i and compareIndex
wordArray[compareIndex] = wordArray[i];
wordArray[i] = longerWord;
}
}
}
//calling sharedLetters function
for(i = 0; i < N; i++)
{
for(compareIndex = 0; compareIndex < N; compareIndex++)
{
string sharedLetters(wordArray[i], wordArray[compareIndex]);
}
}
string word = string sharedLetters(wordArray[i], wordArray[compareIndex]);
cout << word << endl;
//compare every word in wordArray to every other word within the array, using the sharedLetters funtion
for (int i = 0; i < N; i++)
{
for (int compareIndex = i + 1; compareIndex < N; compareIndex++)
{
//saving a string result within the main function that will equal
//the return value of the called function in the previous step
wordsIntersect[i][compareIndex] = sharedLetters(wordArray[i], wordArray[compareIndex]);
}
}
for (int i = 0; i < N; i++)
{
for (int compareIndex = i + 1; compareIndex < N; compareIndex++)
{
cout << wordArray[i] << "," << wordArray[compareIndex] << " " << wordsIntersect[i][compareIndex] << endl;
}
}
return 0;
}
//setting up 2D array wordsIntersect
for (int i = 0; i < N; i++)
{
for (int compareIndex = 0; compareIndex < N; compareIndex++)
{
wordsIntersect[i][compareIndex];
}
}
//writing the data in 2-D array into file wordsIntersect.csv
cout << "Now opening the file wordsIntersect.csv." << endl;
ofstream outputFile;
outputFile.open("wordsIntersect.csv");
cout << "Inputting sorted array wordsIntersect within file, now." << endl;
outputFile << wordsIntersect[i][compareIndex];
//closing file
outputFile.close();
cout << "Data has successfully been entered into the file. The file is now closed." << endl;
return 0;
}
//function that will identify common letters between each word
string sharedLetters(string S1[], string S2[])
{
//declaring string for sharedLetters
string sharedletters = "";
//declaring a string for words with common letters
string commonLetter = "";
//nested for loop to compare letters in S1 and S2
for (int i = 0; i < S1.length(); i++)
{
for (int compareIndex = 0; compareIndex < S2.length(); compareIndex++)
{
//comparing letters in strings
if(S1[i] == S2[compareIndex])
{
//assigning the letter at index i whenever common is found
commonLetter = S1[i];
//adding the value of commonLetter to sharedletters
sharedletters = commonLetter;
break;
}
}
}
//return string of sharedletters
return sharedletters;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am a beginner in C++. And I am trying to play with character array in C++. So, I have written this code.
#include <iostream>
using namespace std;
//Main Function
int main()
{
//Variable declaration
char First[30];
char Middle[30];
char Last[40];
//Array to store all names
char Name[70];
//Loop variables
int i = 0, j = 0;
//Reading all the name
cout << "Enter First name: ";
cin >> First;
cout << "Enter Middle name: ";
cin >> Middle;
cout << "Enter Last name: ";
cin >> Last;
//Copies all characters of Last name to fourth array
while (Last[i] != '\0')
{
Name[j] = Last[i];
i++;
j++;
}
//placing a comma in the fourth array and adding a space
Name[j] = ',';
j++;
Name[j] = ' ';
j++;
cout<<"Hello1\n";
//Copies all characters of First name to fourth array
i = 0;
while (First[i] != '\0');
{
Name[j] = First[i];
i++;
j++;
}
//Add a space
Name[j] = ' ';
j++;
cout<<"Hello2\n";
//Copies all characters of Middle name to fourth array
i = 0;
while (Middle[i] != '\0');
{
Name[j] = Middle[i];
i++;
j++;
}
Name[j] = '\0';
//Display the fourth array
cout << Name << endl;
}
The Problem with this code is that i want to print the Full Name of
Name[] array. But it is getting stuck after printing "Hello1" only.
It is not printing anything after "Hello1". It is taking input of all
three names ( in First[] , Middle[] and Last[] ) correctly. So, I
decided to trace out my code from line 1. I got to know that there is
some problem after first while loop as i am trying to print "Hello1"
and "Hello2". The problem is that it is printing "Hello1" correctly
but it is getting stuck for "Hello2". I think that some problem is in
2nd while loop. But i am not getting the error how could i resolve
this.
Please help me regarding this so that it could print the Full Name
correctly.
Ok so, the problem is your while loop, you made the mistake of put a ; in the end of it, which is making an infinity loop and never gets to the second hello.
//Copies all characters of First name to fourth array
i = 0;
while (First[i] != '\0'); // <- Here is your problem
Should be:
//Copies all characters of First name to fourth array
i = 0;
while (First[i] != '\0') { // <- Here is your problem
Edit
Thanks to Gilles-Philippe Paillé who pointed out, in the third while loop also has an semi-colon which should be removed :D
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is the code:
int main(){
string word= "word";
char ciphered[word.length()];
for(int i=0; i<word.length(); i++)
{
int current_position = (int) word[i];
int new_position = current_position + 2;
char this_char = (char) new_position;
ciphered[i] = this_char;
}
string str(ciphered);
cout << str << endl ;
}
When i run this it prints this:
But when i do this:
for(int i = 0; i<sizeof(ciphered); i++)
{
cout << ciphered[i] << endl ;
}
it prints out the same thing but without last three signs and that is correct
but whenever i try to convert this char array to string it adds these last three weird signs and i dont know why
First of all, this:
char ciphered[word.length()];
is not legal C++ code, though gcc may accept it. But second that you do not need really that char array, as you can access individual symbols with std::string itself:
string word= "word";
string ciphered( word.length(), ' ' );
for(int i=0; i<word.length(); i++)
{
ciphered[i] = word[i] + 2;
}
cout << ciphered << endl;
your code prints additional symbols because you did not put null terminator on C-style string and sent it through std::ostream which leads to UB and prints garbage that happens in memory after your char array until it suddenly finds null terminator or crash because of access of invalid memory.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to make a part of the game hangman, where the user inputs a letter and then a loop check for that letter in a random array. If the letter is found, it then couts a changed array including now that letter and offers the user to again, input another letter. It seems for loops are not working since the program doesnt scan the whole array for ever letter inputted. How can I fix this?
int main(){
string guess[25];
string password[5];
srand((unsigned)time(0));
string letters[5] = {"_ ","_ ","_ ","_ ","_ "};
char array[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','r','s','t','u','v','z'};
for(int r = 0; r < 5; r++){
int g = rand() % 24;
password[r] = array[g];
}
cout << endl;
for(int z = 0; z < 25; z++){
cout << "Enter Letter: " << endl;
cin >> guess[z];
for(int b = 0; b < 5; b++){
if(uguess[z] == password[b]){
letters[b] = guess[b];
cout << letters[b];
}else{
cout << letters[b];
}
}
cout << endl;
}
can someone point me in the right direction. Thanks
It always says that the word being guessed if asdfg, but it messes it up very badly, as in doesn't always show the letter, even if it has been guessed, it shows it later.
crke[b] = ugib[b];
This line should be:
crke[b] = ugib[z];
You might want to consider investing some time in learning how to use a debugger, which would've helped you figure it out.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Okay, so my simple project is supposed to search for all the cases that a particular string is found in a .txt file. Case matters, and if the word is found in another word matters.
(Ex: if the word is "the":
valid finds include:
the apple = 1;
the thespian = 2;
invalid finds include:
fourth elephant (the space between th and e)
The apple (Capitalization)
And if the word IS found in a line of the file, I'm supposed to print out the line ONCE.
If it is not found, I'm not supposed to print it at all.
So, for example, one run of my program should output:
Searching for 'the' in file 'test.txt'
2 : that they do not use permeates the [C++] language. Another example
3 : will further illustrate this influence. Imagine that an integer
5 : What bit value should be moved into the topmost position? If we
6 : look at the machine level, architectural designers are divided on
8 : the most significant bit position, while on other machines the sign
9 : bit (which, in the case of a negative number, will be 1) is extended.
10 : Either case can be simulated by the other, using software, by means
# occurrences of 'the' = 13
Unfortunately, I'm getting
Searching for 'the' in the file 'test.txt'
2: that they do not use permeates the [C++] language. Another example
3: will further illustrate this influence. Imagine that an integer
5: What bit value should be moved into the topmost position? If we
6: look at the machine level, architectural designers are divided on
8: the most significant bit position, while on other machines the sign
9: bit (which, in the case of a negative number, will be 1) is extended.
10: Either case can be simulated by the other, using software, by means
11: of a combination of tests and masks.
12:
# occurrences of 'the' = 15
I am NOT understanding why it thinks it found a "the" in lines 11 and 12.
Here is my code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main(int argc, char* argv[]){
//a char pointer is a c-string
//the array is just an array of char pointers
//argv[0] = pointer to the word to search for
//argv[1] = pointer to fileNames
//includes program name # 0, so three args
if (argc == 3){
int wordCounter = 0;
ifstream myFile(argv[2]);
if (!myFile){
cout << "File '" << argv[2] << "' could not be opened" << endl;
return 1;
}
else {
//counts the number of lines in file
int counter = 0;
//holds the new line in the file
char line[100];
//copies string into buffer that is length of word
const char * word = argv[1];
//holds whether found word
bool found = false;
cout << "Searching for '" << word << "' in the file '" << argv[2] << "'" << endl;
//number of chars in a line
int numChar = 0;
//saves every line
while (!(myFile.getline(line, 100)).eof()) {
//starts every new new at not having found the word
found = false;
//read in new line, so increases line counter
counter ++;
numChar = 0;
//find length of line
for (int i = 0; line[i] != '\n' && i < 101; i++){
numChar++;
}
//finds how many times the key word appears in one line
//checks up to a few before the end of the line for the word
if (numChar >= strlen(argv[1])){
for (int i = 0; i < numChar - strlen(argv[1]); i++){
//if the current line letter equals the first letter of the key word
if (line[i] == word[0]){
//continue looking forward to see if the rest of it match
for (int j = 0; j < strlen(argv[1]); j++){
//if word doesn't match break
if (word[j] != line [i+j]){
break;
}
//if matches all the way to end, add counter
if(j == strlen(argv[1]) - 1){
wordCounter++;
found = true;
}
}//end 2ndfor
}
}//end 1stfor
//if the key word has been found, print the line
if (found){
cout << counter << ": " << line << endl;
}
}
}//endwhile
cout << "# occurrences of '" << word << "' = " << wordCounter << endl;
myFile.close();
}//end else
}//end if
return 0;
}//end main
The cause that your programme believes there is a "the" in lines 11 and 12 is
for (int i = 0; line[i] != '\n' && i < 101; i++)
that you check for a newline (which isn't in the buffer, by the way), but not for the terminating 0. So you check the entire 100 characters -- one more actually, since you also check the nonexistent line[100], and count the "the"s left over from previous lines.
for (int i = 0; i < 100 && line[i] != '\0' && line[i] != '\n'; i++)
should fix that.
Check the validity of the index first to avoid undefined behaviour due to invalid memory accesses.
getline(ifstream&,string) would be more efficient to use in your case when reading lines, in some cases the line might go beyond 100 characters(these characters include whitespaces) and mess the count up. This function will read into the string until an endline is encountered
You don't loop through your file correctly, this could cause undefined behavior and in this case add to your strange number of lines, a correct file loop would be:
//program counts the number of lines in a file
getline(myFile,line) //grab the line
while(myFile) //while the filestream is open and reading
{
//manipulate line string
lineCount++;
getline(myFile,line) //re-read in next line
}