12 Replies - 6356 Views - Last Post: 31 July 2012 - 03:23 AM Rate Topic: -----

#1 Red Prince  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 87
  • Joined: 03-June 12

Runtime Error In String...!

Posted 28 July 2012 - 08:16 AM

It is a well-known phenomenon that most people are easily able to read a text whose words have two characters flipped, provided the first and last letter of each word are not changed. For example:

I dn’ot gvie a dman for a man taht can olny sepll a wrod one way. (Mrak Taiwn)

Write a function string scramble(string word) that constructs a scrambled version of a
given word, ran domly flipping two characters other than the first and last one. Then
write a program that reads words from cin and prints the scrambled words.

According to above instruction I create the following program but it is not working fine. I don't understand why this is happening. On hand tracing method, it is working properly and fine. here is my code!
#include <iostream>
#include <string>
#include <time.h>
#include <cstdlib>

using namespace std;

int main()
{
    string str;
    string str1;
    string str2;
    string scrambled_string = "";

    srand(time(0));

    cout << "Enter a sentence: ";
    getline(cin , str);
    int n = str.length();

    for (int i = 0; i < n; i++)
    {
        do
        {
            str1 = str.substr(i , 1);
            i++;
        }
        while (str.substr(i , 1) != " ");

        cout << "str1:  " << str1;
        int j = str.length();

        if (j > 3)
        {
            int x , y;
            do
            {
                x = rand() % j + 1;
                y = rand() % j + 1;
            }
            while (x != y - 1 || x == j);

            string first = str1.substr(0 , x);
            string last = str.substr(y + 1, j - y - 1);
            string middle = str1.substr(x + 1 , y - x - 1);
            str2 = first + str1.substr(y , 1) + middle + str1.substr(x , 1) + last;
        }
        else
        {
            str2 = str1;
        }
        scrambled_string = scrambled_string + str2;
    }

    cout << scrambled_string;

    return 0;
}


Help me to get rid from this situation. I am using Code::Block and when I am build and run this code i get the following line after entering the sentence...!!

This application has requested to Run-time to terminate it in an unusual way. Please contact the application's support team for more information

Is there any problem with my code or I really contact to application's support team....!!

Is This A Good Question/Topic? 0
  • +

Replies To: Runtime Error In String...!

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2153
  • View blog
  • Posts: 3,315
  • Joined: 21-June 11

Re: Runtime Error In String...!

Posted 28 July 2012 - 08:27 AM

One problem I can see is that your first do-while loop may access the string out of bounds: You check that i is smaller than n in the for-loop, but in the do-while you then increase i without making sure that it's still smaller than n. So if you're in the last word of the sentence (and that word is not followed by a space), i will eventually become equal to n leading to an out of bounds access.

If you still get a runtime error after fixing that, you should use a debugger to find out where and when the program crashes and what the variables' values are when it does.
Was This Post Helpful? 0
  • +
  • -

#3 jimblumberg  Icon User is online

  • member icon


Reputation: 4280
  • View blog
  • Posts: 13,443
  • Joined: 25-December 09

Re: Runtime Error In String...!

Posted 28 July 2012 - 08:28 AM

I see several things wrong with your code. First you need to remember that in C/C++ things like arrays and strings are zero based. Which means that they start at zero and stop at size -1. Now look at how you are using your rand() function to assign random values. Next when you use the substr() function you must insure that the first parameter is equal to or less than the size of your string.

I recommend that you run this program thru your debugger, it will tell you exactly where it detects the problem and you will be able to view the contents of your variables at the time of the crash.

Jim
Was This Post Helpful? 0
  • +
  • -

#4 jimblumberg  Icon User is online

  • member icon


Reputation: 4280
  • View blog
  • Posts: 13,443
  • Joined: 25-December 09

Re: Runtime Error In String...!

Posted 28 July 2012 - 10:36 AM

Also I don't actually see a need to use substr() to accomplish your goals, you just need to swap 2 of the letters within your string, keeping the first and last elements constant. So first insure that the string is larger than 3 characters, and then get one random number to use as the starting position and then swap that character with the next character. Also insure that this second character is not the last character of your string.

Jim
Was This Post Helpful? 0
  • +
  • -

#5 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3662
  • View blog
  • Posts: 11,472
  • Joined: 05-May 12

Re: Runtime Error In String...!

Posted 28 July 2012 - 11:57 AM

View PostRed Prince, on 28 July 2012 - 08:16 AM, said:

It is a well-known phenomenon that most people are easily able to read a text whose words have two characters flipped, provided the first and last letter of each word are not changed. For example:

I dn’ot gvie a dman for a man taht can olny sepll a wrod one way. (Mrak Taiwn)

I'm sorry. I like to nitpick instructions. (I'll never make a good client facing sales person for consulting firm trying to land a contract.)

Is it "well known" as in a scientific fact? Or "well known" as in a Internet meme? Where's the scientific studies?

How does "Taiwn" satify the "two characters flipped" rule?
Twain
Taiwn



The legal flips for it that I see are:
Tawin
Twian



Of course, all this changes if the word was "swapped" instead of "flipped". With "swap" you can exchange two letters which are not adjacent to each other. I seems Jim, like me, also understood the word "flip" to mean exchanging adjacent letters.

And then it gets a little fuzzy with "dn'ot". Is the apostrophe considered a character or punctuation? If the apostrophe is a character, then that was not a legal flip.

If it is punctuation, does the rules for flipping also allow you to move the apostrophe where ever you want? For example:
fo'c'sle --> f'ocls'e
Santa Claus is comin' to town. --> Satna Calus is coim'n to twon.

Additionally, if punctuation needs to be considered, does the code need to distinguish between punctuation that is part of a word, versus punctuation that is part of a sentence?

Anyway back on topic:
Your code only seems to be using white space to break words. The instructions said:

View PostRed Prince, on 28 July 2012 - 08:16 AM, said:

Write a function string scramble(string word) that constructs a scrambled version of a given word, randomly flipping two characters other than the first and last one. Then write a program that reads words from cin and prints the scrambled words.

To me, this means something as simple as:
while(true)
{
    string word;
    cout >> "Enter a word to be scrambled: ";
    cin >> word;
    cout << scramble(word) << endl;
}


without needing to break on whitespace.

Of course, your teacher may have amended the instructions where you are supposed to take entire lines. If that is the case, then breaking on whitespace isn't going to be enough. Consider what the input would have been from the original post:

Quote

I don't give a damn for a man that can only spell a word one way. (Mark Twain)

If you were breaking on whitespace, you would end up with words like "way.", "(Mark" and "Twain)". You will need to be more discriminating about breaking words. And it'll get very interesting dealing with compound words like "merry-go-round".

This post has been edited by Skydiver: 28 July 2012 - 11:58 AM

Was This Post Helpful? 0
  • +
  • -

#6 Red Prince  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 87
  • Joined: 03-June 12

Re: Runtime Error In String...!

Posted 29 July 2012 - 12:57 AM

@seep2k
you are right I am going in a a wrong way with substr(). after that I modify my program which I will post at the end.

@ Jim
I do this but I'll also get the error. How can you swap two characters in a word without substr(). your logic for getting two random numbers is good but if you read the question it says choose two random numbers from the word other than first and last. if words length is 7 then two random numbers can be 1 , 5 or 2 , 5 but can't 1 , 6 or 2 , 6.

@ skydiver
You are right about word dn'ot but in the question it is given as I post....!! Secondly, from the question it is clear that punctuation and special characters are not swapped/flipped. I don't know how to get words from a string. Is there is a function like pow() or substr() to this task or I have to modify my program. Because while fetching words from merry-go-round it is not possible to get merry , go and round separate.
Also, this question is not from my teacher. I am learning C++ from a book named C++ for every one written by Cay Horstmann. This question is in the book exercise of chapter function.

Additionally, I modify my program and it works for the sentence given in the question which is :
I don't give a damn for a man that can only spell a word one way. (Mark Twain)
but this code swapped the word way. as wya. and (Mark) as (aMrk)
here is my modified code...!!

#include <iostream>
#include <string>
#include <time.h>
#include <cstdlib>

using namespace std;
/**
    This will return a word from a sentnce....!!
    @param str The sentence from which word is taken.....!!
    @param i From where in the sentence words is being fatching...........!!
    @param length of str......!!
    @return str1 word which is fetchinf from te given sentence......!!
*/
string Substring(string str , int& i , int n)
{
    string str1 = "";
    do
    {
        str1 = str1 + str.substr(i , 1);
        i++;
    }
    while (str.substr(i , 1) != " " && i != n);

    return str1;
}

int main()
{
    cout << "Enter a sentence: ";
    string str;
    getline(cin , str);

    int n = str.length();
    string scrambled_string = "";

    for (int i = 0; i < n; i++)
    {
        string str1 = Substring(str , i , n);

        int j = str1.length();

        string str2;

        if (j > 3)
        {
            int x = 1 , y = 2;

            string first = str1.substr(0 , x);
            string last = str1.substr(y + 1, j - y - 1);
            str2 = first + str1.substr(y , 1) + str1.substr(x , 1) + last;
            cout << "j = " << j << " 1st : " << first << "  last : " << last << " str2 : " << str2 << "(x ,1) : " << str1.substr(x , 1) << "(y , 1): " << str1.substr(y , 1) << endl;
        }
        else
        {
            str2 = str1;
        }

        scrambled_string = scrambled_string + " " + str2;
    }

    cout << scrambled_string;

    return 0;
}



I am working on it and want to guidance from you....!!!
Was This Post Helpful? 0
  • +
  • -

#7 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3662
  • View blog
  • Posts: 11,472
  • Joined: 05-May 12

Re: Runtime Error In String...!

Posted 29 July 2012 - 01:10 AM

For distinguishing between characters, punctuation, and whitespace, there are C/C++ functions:
isspace(): http://en.cppreferen...ng/byte/isspace
ispunct(): http://en.cppreferen...ng/byte/ispunct
isalpha(): http://en.cppreferen...ng/byte/isalpha
Was This Post Helpful? 0
  • +
  • -

#8 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3662
  • View blog
  • Posts: 11,472
  • Joined: 05-May 12

Re: Runtime Error In String...!

Posted 29 July 2012 - 01:23 AM

View PostRed Prince, on 29 July 2012 - 12:57 AM, said:

@ Jim
I do this but I'll also get the error. How can you swap two characters in a word without substr(). your logic for getting two random numbers is good but if you read the question it says choose two random numbers from the word other than first and last. if words length is 7 then two random numbers can be 1 , 5 or 2 , 5 but can't 1 , 6 or 2 , 6.


I'm not Jim, but I am nitpicky. The question did not say "choose two random numbers(sic) from the word other than first and last." It said:

Quote

Write a function string scramble(string word) that constructs a scrambled version of a given word, randomly flipping two characters other than the first and last one.


This means that if word length is seven, you pick a random number between 1 and 4 inclusive. After picking a number, flip with the succeeding letter. So given the word "admiral", the options are:
1: amdiral
2: adimral
3: admrial
4: admiarl



This is why the word "don't" becomes a sticking point given the directions. How did it manage to flip a pair of characters more than once? And as I mentioned before, how did it manage to flip a pair of characters more than one for "Twain"?
Was This Post Helpful? 0
  • +
  • -

#9 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3662
  • View blog
  • Posts: 11,472
  • Joined: 05-May 12

Re: Runtime Error In String...!

Posted 29 July 2012 - 01:28 AM

As for "merry-go-round", the word is a compound word and should be treated as a single word.

The same is true for the open compound word: "attorney general" or "post office".

For more about compound words, see: http://grammar.ccc.c...r/compounds.htm
Was This Post Helpful? 0
  • +
  • -

#10 Red Prince  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 87
  • Joined: 03-June 12

Re: Runtime Error In String...!

Posted 29 July 2012 - 05:10 AM

@skydiver
I read all your links but these are for Character data type not for String data type. and I want to use string data type....!!
Was This Post Helpful? 0
  • +
  • -

#11 jimblumberg  Icon User is online

  • member icon


Reputation: 4280
  • View blog
  • Posts: 13,443
  • Joined: 25-December 09

Re: Runtime Error In String...!

Posted 29 July 2012 - 06:45 AM

A string is composed of individual characters, so the isspace(), ispunct(), and isalpha() functions are appropriate when dealing with the individual characters.

Now remember that the first and last characters must remain in the same position. With this constraint your word must be equal to or greater than 4.

Did your instructor give you the examples you have provided? Because to me the examples and your explanation of the assignment have inconsistencies, that Skydiver and I have already mentioned.

Quote

Write a function string scramble(string word) that constructs a scrambled version of a
given word, randomly flipping two characters other than the first and last one.

The sticking point is how your instructor defines "flipping", I and Skydiver interpret this to mean "swap two consecutive characters", but this doesn't work given your example. But if your instructor interprets flipping as "take any two characters except the first and last and exchange them" the examples will work.

Now given the example sentence and the inconsistencies noted with the definition of "swap two consecutive characters" I would take the meaning to be "take any two characters except the first and last and exchange them". With this definition you would indeed then need two different random numbers that are in the correct range.

For example for a word with a length of 5 (Twain) you will need two random numbers between 1 and 3, since the first letter (letter[0]) and the last letter (letter[4]) must remain constant. With this definition I would also say that the the thing that separate a "word" would be a space, and sentence punctuation marks. For the contraction the punctuation mark (') would be considered part of the word but, a comma or period would not be part of your "word".

Jim

This post has been edited by jimblumberg: 29 July 2012 - 06:48 AM

Was This Post Helpful? 0
  • +
  • -

#12 Red Prince  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 87
  • Joined: 03-June 12

Re: Runtime Error In String...!

Posted 31 July 2012 - 01:20 AM

Hello, Sorry for late reply. Actually, Due to Ramadan I am busy. In Ramadan Study is a little bit difficult. But I'm trying to manage it.....!!!
Come back to topic....!!

Quote

As jim said
A string is composed of individual characters, so the isspace(), ispunct(), and isalpha() functions are appropriate when dealing with the individual characters.

I really don't understand/know how to use these function. Because these function are get only one character at a time. So, if we use string then how can we use these functions. Can you please tell me or post a simple program that use all these function. I'll be thank full to you...!!

Now, I create a program that runs in a good way (for me. may be I am wrong) and I use a function int length(string str) to clear all punctuations from a word (means it reduces the length of word so that we choose a random function form a word. here is my code:

#include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>

using namespace std;

int length(string str)
{
    int n = str.length();
    for (int i = 0; i < n; i++)
    {
        if (str.substr(i , 1) == "." || str.substr(i , 1) == "?" || str.substr(i , 1) == "-" || str.substr(i , 1) == "_" ||
            str.substr(i , 1) == "'" || str.substr(i , 1) == "!" || str.substr(i , 1) == "(" || str.substr(i , 1) == ")")
            n--;
    }
    return n;
}

/**
    This will return a word from a sentnce....!!
    @param str The sentence from which word is taken.....!!
    @param i From where in the sentence words is being fatching...........!!
    @param length of str......!!
    @return str1 word which is fetchinf from te given sentence......!!
*/
string Substring(string str , int& i , int n)
{
    string str1 = "";
    do
    {
        str1 = str1 + str.substr(i , 1);
        i++;
    }
    while (str.substr(i , 1) != " " && i != n);

    return str1;
}

int main()
{
    string str;
    cout << "Enter a sentence: ";
    getline(cin , str);

    int n = str.length();
    string scramble;

    for (int i = 0; i < n; i++)
    {
        string str1 = Substring(str, i, n);
        int j = length(str1);
        string str2;

        if ( j > 3)
        {
            int x , y;
            if (str1.substr(0 , 1) == "." || str1.substr(0 , 1) == "?" || str1.substr(0 , 1) == "-" || str1.substr(0 , 1) == "_" ||
                str1.substr(0 , 1) == "'" || str1.substr(0 , 1) == "!" || str1.substr(0 , 1) == "(" || str1.substr(0 , 1) == ")")
                {
                    x = 2;
                    y = 3;
                }
                else
                {
                    x = 1;
                    y = 2;
                }

            string first = str1.substr(0 , x);
            string last = str1.substr(y + 1, j - y);
            str2 = first + str1.substr(y , 1) + str1.substr(x , 1) + last;
        }
        else
        {
            str2 = str1;
        }

        scramble = scramble + " " + str2;
    }

    cout << scramble;

    return 0;
}


Also I find that the runtime error is occur due to rand() function because when I use rnad()function Code::Blcok generate an error but if we don't use this than all program run correctly...!! Here is also my rand() usage;

int x ,y;
            if (str.substr(i , 1) == "." || str.substr(i , 1) == "?" || str.substr(i , 1) == "-" || str.substr(i , 1) == "_" ||
                str.substr(i , 1) == "'" || str.substr(i , 1) == "!" || str.substr(i , 1) == "(" || str.substr(i , 1) == ")")
            {
                do
                {
                    x = rand() % j + 2;
                    y = x + 1;
                }
                while (x > y || y == j);
            }
            else
            {
                x = rand() % j + 1;
                y = x + 1;
            }
            while (x > y || y == j);


or I use it as a function like this:
void random(string str, int& x, int& y, int j)
{
     if (str.substr(0 , 1) == "." || str.substr(0 , 1) == "?" || str.substr(0 , 1) == "-" || str.substr(0 , 1) == "_" ||
         str.substr(0 , 1) == "'" || str.substr(0 , 1) == "!" || str.substr(0 , 1) == "(" || str.substr(0 , 1) == ")")
                {
                    do
                    {
                        x = rand()% j + 2;
                        y = x + 1;
                    }
                    while (x > y || y == j);
                }
                else
                {
                    do
                    {
                        x = rand() % j + 1;
                        y = x + 1;
                    }
                    while (x > y || y == j);
                }
}


I don't understand why this is happening......!!!
Moreover, As, Skydiver said that:

Quote

As for "merry-go-round", the word is a compound word and should be treated as a single word.

The same is true for the open compound word: "attorney general" or "post office".

For more about compound words, see: http://grammar.ccc.c...r/compounds.htm


I'll try to modify my program so that it works for compound words. But kindly tell me my logic is right or not....!!
Was This Post Helpful? 0
  • +
  • -

#13 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3662
  • View blog
  • Posts: 11,472
  • Joined: 05-May 12

Re: Runtime Error In String...!

Posted 31 July 2012 - 03:23 AM

Forget about compound words for now.

You can access the individual letters of a string and get back a char:
string s = "five o'clock";
for(int i = 0; i < s.length(); i++)
    cout << s[i] << endl;


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1