Question

In: Computer Science

Hi! I wrote two function to get count cluster of char in a string , charFreq(),...

Hi! I wrote two function to get count cluster of char in a string , charFreq(), and an other one which iterate through a vector line by line looking for last element on each line, last(). The problem is, after appending all chars in a string and try to count clusters of values in that string, I get seg fault. I feel like my logic behind is ok, but I am not sure what I did wrong. Can someone help and tell me where are my errors. Also, all computation are done on txt file.

-----------------------------------------------------------------------------:c++ program

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

#include <fstream>

using namespace std;

//func to check frequency of a char in a string

void charFreq(string& Mystring){

int w = 1;

vector<int> count; //store all freq int into a vector

for(int i = 0; i <= Mystring.length(); i++){

if(Mystring.at(i)== Mystring.at(i+1))//if two adjacent value are the same increment my w: aaa = 3a

{

w++;

count[i]=w;

}

}

//print out all int charFreq.

for(int x = 0; x < count.size()-1; x++){

cout << count[x]<<" ";

}

}

void printArray(vector<string> array) {

for (int i = 0; i < array.size() - 1; ++i)

cout << array[i] << endl;

}

//iterate through vector looking for last char and append all chars into one string

string last(vector<string>& line){

char w;

string x;

string y = " ";

for(int i = 0; line.size(); i++){

w = x.at(x.length()-1);//find last char in a string

y += w;//append my char to a string

}

return y;//return entire string of appended chars

}


int main(int argc, char *argv[])

{

string i;

string input_line;

vector<string> value;

ifstream infile("Freq.txt");

if (infile.is_open())

{

while (getline(infile, input_line))

{

for (int i = 0; i < input_line.size(); i++)

{

value.push_back(input_line);//push individual input_line into vector value

charFreq(input_line);

printArray(value);

last(value);

}

}

infile.close();

}

return 0;

}

------------------------------------------------------------------------------------------------Freq.txt file

there!Hi

!Hi there

Adios

Hi there!

diosA

e!Hi ther

ere!Hi th

here!Hi t

i there!H

iosAd

osAdi

re!Hi the

sAdio

---------------------------------output

1i 1e 1s 1!.........................1o

Solutions

Expert Solution

/*
you did wrong in for loop where "i=Mystring.length()"
when i=Mystring.length() and you write Mystring.at(i+1) which is illegal memory access/
prompt to segmentation fault.
*/

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>

using namespace std;

//func to check frequency of a char in a string

void charFreq(vector<char> & Mystring)
{
int hash[128]={};
//store all freq int into a vector

for(int i = 0; i <Mystring.size(); i++)
{
hash[Mystring.at(i)]++;
for(int j=i+1;j<Mystring.size();j++)
{
if(Mystring.at(i)==Mystring.at(j))
{
hash[Mystring.at(i)]++;
}
}
}
for(int i=0;i<128;i++)
{
if(hash[i]>=1)
cout<<(char)i<<" "<<hash[i]<<endl;
}
}

void printArray(vector<char> &array) {

for (auto i = array.begin(); i != array.end(); ++i)
cout << *i ;
cout<<endl;
}

char last(string &line){

if(line.length()>0)
return line.at(line.length()-1);//return entire string of appended chars
return '~';

}


int main(int argc, char *argv[])
{
string i;
string input_line;
vector<char> value;
ifstream infile("Freq.txt");
if (infile.is_open())

{

while (infile)

{

getline(infile, input_line);
if(input_line.length()>0)
value.push_back(last(input_line));//push individual input_line into vector value

}
printArray(value);
charFreq(value);
infile.close();

}
return 0;
}


Related Solutions

I am trying to tokenize a string using a function by passing the char string[] and...
I am trying to tokenize a string using a function by passing the char string[] and char *pointer[100]. While I have working code inside the int main(), I am having trouble actually declaring the parameters for the function. I know how to pass the char array (char string[]), but not how to pass the char pointer array (char *pointer[100]). This is my code below: int main() {    // Declare variables    char str[] = "this is a test only...
There is a C function decodeMorse(const String & string, char message[]). This function examines the binary...
There is a C function decodeMorse(const String & string, char message[]). This function examines the binary string and iteratively constructs a decimal value (val) and width of each binary pattern (separated by spaces), until a space or a null character ('\0') is encountered in the string. Once a space or a null character is found, this function should call the assembly code (decode_morse()) to obtain the corresponding ASCII value, for the current val and width, and place the ASCII value...
public class StringTools {    public static int count(String a, char c) {          ...
public class StringTools {    public static int count(String a, char c) {           }
I wrote this program to check a string is palindrome or not. but in both cases,...
I wrote this program to check a string is palindrome or not. but in both cases, it gives me palindrome. could someone help me with this program? it has an error I couldn't find. when I run the code and give a string, in both cases it gives me palindrome. for example if I give Pop it says it is a palindrome but if I give Salima, it also says palindrome. #include<string> #include <iostream> using namespace std; class PString:public string...
Write a recursive Racket function "remove-char" that takes two string parameters, s and c, and evaluates...
Write a recursive Racket function "remove-char" that takes two string parameters, s and c, and evaluates to string s with all occurrences of c removed. The string c is guaranteed to be a length-1 string; in other words a single character string. For example (remove-char "abc" "b") should evaluate to "ac". Here is pseudocode that you could implement.
Hi, I need to finish function purser,which will include header row and i can get same...
Hi, I need to finish function purser,which will include header row and i can get same output /* [ { firstName: 'moe', lastName: 'green' }, { firstName: 'lucy', lastName: 'liu' }, { firstName: 'ethyl', lastName: 'mertz' } ]*/ In javascript please const parser=(d)=>{ let arr=[]; let newArr=[]; let obj={} let items=d.split('|'); for (let i=0;i<items.length;i++){ arr[i]=items[i].split(','); } for (let z=0;z<arr.length;z++){ newArr=newArr.concat(arr[z]); } for(var y = 0;y < newArr.length;y+=2){ obj[newArr[y]]= newArr[y+1]; } //const res = newArr.reduce((a,b)=> (a[b]='',a),{}); return obj; } const data...
Implement function noVowel() that takes a string s as input and returns True if no char-...
Implement function noVowel() that takes a string s as input and returns True if no char- acter in s is a vowel, and False otherwise (i.e., some character in s is a vowel). >>> noVowel('crypt') True >>> noVowel('cwm') True >>> noVowel('car') False Implement function allEven() that takes a list of integers and returns True if all integers in the list are even, and False otherwise. >>> allEven([8, 0, -2, 4, -6, 10]) True >>> allEven([8, 0, -1, 4, -6, 10])...
I have a char memory[1024]. I want to write the string "mike" into the memory starting...
I have a char memory[1024]. I want to write the string "mike" into the memory starting from an index. I also need a function to move "mike" to another index in the same memory swapping m and k in mike. Basically, i need a function to write to memory and a function to move the string to an index. Thank you In c++ please.
I am running this code using C to count the words in char array, but somehow...
I am running this code using C to count the words in char array, but somehow it keeps counting the total characters + 1. Any solution to fix this problem? #include <stdio.h> int main() {    char input[1001];    int count =0;    fgets(input, 1001, stdin);    char *array = input;    while(*array != '\0')       {        if(*array == ' '){            array++;        }        else{        count++;        array++;...
Write a function void reverse(char * s) that reverses the string passed as an argument. Your...
Write a function void reverse(char * s) that reverses the string passed as an argument. Your code should use pointer arithmetic (it may increment and decrement pointers, but it may not use array indexing). Here is a piece of code that shows the behavior of reverse: char buf[100]; strcpy(buf, “hello”); reverse(buf); printf(“%s\n”, buf); // output should be olleh
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT