Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

There is segmentation fault in this code and I don\'t know where or how to fix i

ID: 3550828 • Letter: T

Question

There is segmentation fault in this code and I don't know where or how to fix it. The purpose of this code right here is to grab the tokens from the token vecctor and find single quotes. Then combine the single quote string into one token and the fix the rest of the token vector.


Example:

Label Code C'Program 5' test

This should be four tokens


Fix the code or give me a replacement.



void file_parser::check_quote(vector<string> tokens)

{

bool has_quote = false;

string tmpstr;

unsigned int FirstQuote = 0;

unsigned int SecondQuote;

string tmp;

string tmpstr2;

for (unsigned int i = 0; i <= tokens.size() - 1; i++) {

tmp = tokens[i].c_str();

for (unsigned int m = 0; m <= tmp.size() - 1; m++) {

if (tmp[m] == ''') {

has_quote = true;

FirstQuote = m;

}

if (has_quote && m != FirstQuote && tmp[m] == ''') {

SecondQuote = m;

for (unsigned int k = FirstQuote; k <= SecondQuote; k++) {

tmpstr += tokens[k];

}

tokens.insert(tokens.begin() + FirstQuote, tmpstr);

for (unsigned int j = FirstQuote + 1; j <= tokens.size() - 1; j++) {

for (unsigned int l = SecondQuote + 1; l <= tokens.size() - 1; l++) {

tmpstr2 = tokens[SecondQuote + 1];

tokens.insert(tokens.begin() + j, tmpstr2);

}

}

int test = tokens.size() - SecondQuote + 1;

while (test > 0) {

tokens.erase(tokens.end() - 1);

}

}

}

}

}

Explanation / Answer

This will work perfectly.


#include<iostream>

#include<vector>

using namespace std;


int quote_count(string& str){

int c = 0, i;

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

if(str[i] == ''') c++;

}

return c%2;

}


void check_quote(vector<string>& tokens)

{

bool has_quote = false;

string tmpstr;

int FirstQuote = -1;

unsigned int SecondQuote;

string tmp;

string tmpstr2;

for (unsigned int i = 0; i <= tokens.size() - 1; i++){

tmp = tokens[i].c_str();

if(has_quote && quote_count(tmp)){

for (unsigned int k = FirstQuote; k <= i; k++) {

tmpstr += tokens[k];

}

tokens[FirstQuote] = tmpstr;

for (unsigned int j = FirstQuote + 1; j <= i; j++) {

tokens.erase (tokens.begin()+j);

}

i = FirstQuote+1;

has_quote = false;

}

else if(quote_count(tmp)){

has_quote = true;

FirstQuote = i;

}

}

}


int main(){

vector<string> vv;

int i;

vv.push_back("abcd");

vv.push_back("asho'k");

vv.push_back("kum'a'r");

vv.push_back("goo'd");

check_quote(vv);

for(i=0; i<vv.size(); i++){

cout<<vv[i]<<endl;

}

return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote