Deadly error in vector code

"This application has requested the run-time terminate in an unusual way."

I am freelance trying to run through Stroustrups principles and practice in c++ programming book. this specific program which is designed to give you back all the words that you input in order in a list in order, terminating repeated words.

This is the initial code for this simple program. (not including libraries

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
	vector<string> words;
	string word;

	

	while (cin>>word)
    
          words.push_back(word);  // add entered strings to the vector
          cout << "Number of words: " << words.size() << endl;
  	sort(words.begin(),words.end()); 
  	
			for (int i = 0; i<words.size(); ++i)
			
		     if (i==0 || words[i-1]!=words[i] )  // is this a new word?
                cout << words[i] << endl;
                
system("PAUSE");
}







This works fine and i have no problems with it, you input some words and then you press enter and on then press ctrl+z which isnt recognized as a string so it terminates the loop and performs the for loop.

--------------------------------------------------------------------------------


So here is the real issue.

In the book he asks you to "TRY THIS!" where he says that you should try to make a program that does what this does, but add on some code which would make it so that if any undesirable words were uttered, they would be bleeped out..

i think i may have failed miserably but ill explain my "logic" for trying to get this to work. If im terribly wrong then maybe someone could point me in a better direction for accomplishing this.(this isnt some homework assignment of mine dont worry, i do this for fun)

Here is my guess at a program that can censor unwanted words.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <iostream>
using namespace std;


int main()
{
	vector<string> words;
	string word;
	string badword = "bananas";
        string goodword = 0;
 
 cout << "This program records every word you type and records them in order."
      << endl
      << "This program will also bleep out any unlike words."
      << endl
      << "What word would you like to have replace any bad words?"
      << endl
      << "------>";
 cin  >> goodword; 
 cout << "go!";
	

	while (cin>>word)
    
          words.push_back(word);  // add entered strings to the vector
          cout << "Number of words: " << words.size() << endl;
  	
	sort(words.begin(),words.end()); 
			for (int i = 0; i<words.size(); ++i)
			
			 
			    
		     if (i==0 || words[i-1]!=words[i] || words[0,word.size()]== badword) { // is this a new word?
               badword = goodword;
                cout << words[i] << endl;
                }
system("PAUSE");
}


Basically my thoughts here were this..

I declared some string variable named badword and defined it with the string "bananas". so if bananas is input its turned into a "goodword"
Then i declared an empty variable named "goodword"

I give the user some directions then prompt him to give a word that would replace "badword" with "goodword"

at the end i added another condition which was that if any of the words in the vector from range 0 to words.size() = badword then it would change it to the good word..

the program will run and the console comes up but it stops responding and gives a terminating error and prompts me to locate the application team (me) for any questions lol.

even though im not sure that would work at all just a guess. im very new to programming.


Any hints or tips would be nice sorry if this is extremely noob or seems like a dumb question to any of you, im just learning.

Line 15: string goodword = 0? You cannot assign an integer to a string. Get rid of the "=0" part. Strings are initialized to empty strings by default.

Line 38: word[0,word.size()] isn't really defined in C++. I'm not sure what you were going for there. It should probably be word[i]. But the logic is wrong. You want to check word[i] == badword inside the old if clause and reassign word[i] = goodword.

When i was assigneing the string to 0 i was mistakenly thinking i was assigning it to a mutable value. i thought 0 was usable but i was mistaken you either leave it blank or put a = " ";
And aparently that was the reason it was giving me the error.
So i figured that out already, thanks.


And i guess what i thought i was doing with

word[0,word.size(0)] == badword

was that i thought i was asking the program to scan through vector 0 all the way to the last vector (which would be the vector size) and see if it was a badword, and if that was tre then change badword into good word... I dont know why i thought i was telling it to check all strings in v0 to v.size()

so scratch that
I changed it to this but apparently its not assigning bananas to the word im putting in to replace it.

1
2
3
4
  if (i==0 || words[i-1]!=words[i] || words[i]== badword) { // is this a new word?
               badword = goodword;
                cout << words[i] << endl;
                }


So, whatever is happening it isnt assigning anything represents badword to goodword.

Any suggestions on how i could accomplish this?
oh ok i understood what i did wrong but when change it to this...

1
2
3
4
 if (i==0 || words[i-1]!=words[i] || words[i]== badword) { // is this a new word?
               words[i] = goodword;
                cout << words[i] << endl;
                }


all this does it change the entire index to the word i pick, I picked happy.. and its just showign up like this...

i put in: "bananas are the best!"

its shows:
happy
happy
happy
happy

"Deadly error"?

Who has this killed?
To be fair, who were killed by all those "fatal errors"?
After working with a compiler that doesn't emit warning or errors when it should, I don't begrudge good compilers a little exaggeration when they do come across problems.
These errors killed your abilities to be funny, I think.



There's nothing funny about it. Your choice of terminology needs help.

A "fatal error" is one in which the application process is "terminated".

A "deadly error" is one in which people die.
I suggest taking a look at the standard library function std::replace?

I think that, if you add the following, it will fulfil your objectives.

 
replace( words.begin(),words.end(), badword, goodword );


You could remove the "sort" entirely, since replace does not need that - but I wasn't sure whether you also wanted the words sorted.

Another point is that your method of tokenizing the input string regretably does not handle other words or symbols. So for your test input "bananas are the best!" the tokens are:
1
2
3
4
bananas
are
the
best!


This means that if your input string contained those symbols next to the word you wanted to remove, your code would fail to spot that string (e.g. try "bananas! are the best").

If you want to do the same there you must either tokenize in a more detailed way (perhaps splitting out the symbols into separate tokens) and stick with "std::replace" or you can probably use one of the predicate methods for "std::transform" which allows a smarter control of what to match and what to replace.

Hope this helps,
CC
Last edited on
Just to demonstrate what I meant about the "std::transform":
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Transformer
{
private:
	std::string const m_pattern;
	std::string const m_replacement;

public:
	Transformer( std::string const & pattern, std::string const & replacement )
		: m_pattern( pattern )
		, m_replacement( replacement )
	{
	}

	std::string operator ( )( std::string const & element ) const 
	{
		std::string::const_iterator it = std::search( element.begin(), element.end(), m_pattern.begin(), m_pattern.end() );
		if( it != element.end() )
		{
			std::size_t lhs = std::distance( element.begin(), it );
			std::size_t rhs = lhs + m_pattern.size();
			return element.substr( 0, lhs ) + m_replacement + element.substr( rhs, element.size() - rhs );
		}
		return element;
	}
};


Then we just replace the "std::replace" function like so:
 
transform( words.begin(),words.end(), words.begin(), Transformer( badword, goodword ) );


Hope this doesn't confuse!
CC
Douas
Your comment is laughable, considering that ultimately fatal and deadly are synonyms. regardless of the fact that fatal is also used in computer terminology whereas deadly not so much..

So, I dont need a lecture on terminology, you obviously don't know how to pull understanding out of someone else's expression without projecting your own set of "how you should express yourself" upon that person.

And in all fair judgment, If you were to look at my post and actually were to come to the conclusion that someone seriously may have died... then you have some serious issues with interpretting what other people mean, let alone understanding the actual words they use.. and that might demand the application of some type of psychological therapy. Or furthering your education might be all it takes.

How about we either post on the problem presented if we feel like it, without trying to control other's style of grammar (which isnt really that hard to be honest), OR! we just ignore the post and move on! =D

This would delete the illusion that some people have so many posts because they are actually helping in some way. Because the truth is although someone like you might have 3000+ posts in this forum, I would argue that much like the posts you've left here, a considerable amount of those posts are tributed to problem creating, rather than problem solving. so... Ill say what i want, how i want, using the punctuation i prefer, until you or someone else comes and puts a gun to my head, and even then i still might fight back. =)))

BIG DEEP BREATH.

---------------------------------------------------------------------------------------------------------------------------


Corroded coder thanks alot for that bit you added, and i just got back on this problem since i was last on.

from what im understanding, The words need to be sorted in order for it to go back and see if any words repeat themselves. The vector calls to check if that unit of memory is the same as last, this all has to be done AFTER it is sorted alphabetically using begin() and end() functions. Im trying to acheive both things, i wanted the words in "order" and for the chosen word to be replaced.


I dont really understand your post since im pretty new to all of this, but thanks for trying. sorry
Wow, I'm really hurt that a noob like yourself is offended when I offer some simple advice on "terminology". The computer world != normal people world. Go get a job and tell them your code has a "deadly error" and see how long your paychecks continue.

Oh, and for the record, I never tried to solve your problem (since you were being helped already), so who's projecting what now? Go away.


BTW, I don't care whether you care, nor do I care about my post count, so don't bother trying any snappy, useless comebacks -- since I won't read them. (It is so hard to pay attention, you know.) Your mind is so obviously beyond my low standard that I'm sure you already know I voted against stupid badges and buttons and counters. "Honesty" indeed. That's what young people call hostile double-talk nowdays? Time for me to just die off, I guess, and let the world self-destruct itself with buggy, broken programs.

Glad I wasn't able to help.
Duoas wrote:
There's nothing funny about it. Your choice of terminology needs help.

A "fatal error" is one in which the application process is "terminated".

A "deadly error" is one in which people die.


Agreed.

A fool wrote:
Ill say what i want, how i want, using the punctuation i prefer, until you or someone else comes and puts a gun to my head, and even then i still might fight back.


Oh god. Reminds me of the internet...oh wait.

Wow duoas dont get your panties in a mix hahaha. I dont think i need any of these "snappy comeback" things you are talking about. I'de say your response to my post illustrates my point..
A little bit of intellectual snobbiness on your part is all this really is. I'm sorry if you have some personal issues brewing inside that makes you want to lash out in a tirade about the proper use of fatal and deadly. hahaha

I could honestly care less who you are and what you think, nor am i going to lose my job for saying deadly.

you fail

Oh god. Reminds me of the internet...oh wait.


you bet.

Last edited on
Can you all stop this non C++ related discussion?
I hate flamewars
Corroded coder thanks alot for that bit you added, and i just got back on this problem since i was last on.

from what im understanding, The words need to be sorted in order for it to go back and see if any words repeat themselves. The vector calls to check if that unit of memory is the same as last, this all has to be done AFTER it is sorted alphabetically using begin() and end() functions. Im trying to acheive both things, i wanted the words in "order" and for the chosen word to be replaced.


I dont really understand your post since im pretty new to all of this, but thanks for trying. sorry


No need to apologize - I think the mistake was mine, I'll try and stick closer to the problem at hand :)

From the textual description you display, it seems like you are claiming you will substitute a "bad" word for the input "good" word.

If that's true, I still don't see why you would change the order of the input words with "sort". I suspect we're having a misunderstanding over the term "in order". Do you mean alphabetical order? If so, I understand why you are sorting the list. The term "in order" on it's own, would tend to imply that you would not change the order.

Perhaps:
1
2
3
4
5
6
7
8
9
10
11
for (int i = 0; i<words.size(); ++i)
{
        if( words[i] == badword )
        {
                cout << goodword << endl;
        }
        else
        {
                cout << words[i] << endl;
        }
}


Or if you want to replace any occurances of "badword" with the "goodword" in the vector itself:
1
2
3
4
5
6
7
for (int i = 0; i<words.size(); ++i)
{
        if( words[i] == badword )
        {
                words[i] = goodword;
        }
}


That last example is functionally equivalent to:
replace( words.begin(),words.end(), badword, goodword );


I apologize if I have misunderstood your problem again - I'm afraid I tend to reply to these last thing at night - and am half way to being asleep :)

Hope this helps,
CC
Last edited on
Yes that helped , I eventually came back to this problem on my own and figured it out using the book, but what you are saying makes sense. I appreciate your help and your adherence to the subject at hand rather then pointlessly digressing to admonish the nature of my vocabulary.

But the sort() and begin() and end() functions I believe are just standard c++ functions and when I have been using them this way it numbers and alphabetizes everything in ascending order.

I've been using a similar program I wrote for fun to organize some keywords and definitions for some flashcards lol :D
Last edited on
Topic archived. No new replies allowed.