1

I'm a C++ starter. I tried writing a code that gets a certain string, for instance - "there1hello0". I tried to make a sentence from it, following this rule:

Each word ends with a number that specifies it's place in the sentence. Therefore the the sentence is: "hellothere".

My code:

void analyze() 
{
    string Given = "there1hello0";
    int flag = 0;
    string word = "";
    string Display[2];

    for (int i = 0; i <= Given.length(); i++) {
        if (isdigit(Given[i])) {
            for (int x = flag; x <= 1; x--) {
                word += Given[i - x];   
            }
            Display[(int)Given[i]] = word;
            word = "";
            flag = 0;
        }
        else {
            flag++;
        }
    }

    for (int z = 0; z <= 1; z++) {
        cout << Display[z];
    }   
}

int main() 
{
    analyze();
    system("pause");
    return 0;
}

I'v included the <string> and <iostream> libraries and used namespace std.

For some reason, I can't figure out. Because I can't really understand exceptions, my code doesn't work and throws the following:

Exception thrown: write access violation. _My_data was 0x7001AC.

Any help would be appreciated.

kvantour
  • 25,269
  • 4
  • 47
  • 72
Mor Katz
  • 51
  • 3
  • 2
    Please learn how to use debugger. These kind of issues can be easily tracked out with it's help. – Mahesh Apr 17 '18 at 19:25
  • Hint: The problem is you are not starting with the index where the digit is found in the loop. – Mahesh Apr 17 '18 at 19:31

1 Answers1

0

You can easily track your error using a debugger. I strongly recommend learning how to use it.
But anyways, there are multiple things wrong with your code. In the first place, you should learn how does for loop work and how you should iterate over the string.

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

should be

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

so instead <= you should use <. Because last element of string is stored on position n-1 if n is length, because you are iterating from 0.

Also in your inner loop

for (int x = flag; x <= 1; x--) {

you are iterating down, so you should be comparing x >= 1 instead of x <= 1.

Also (int)Given[i] returns an ASCII value of char stored in Given[i]. For example if Given[i]='0' then (int)Given[i] will return the ascii value of char '0', namely 48 and not 0 as you would think. You can find more on this problem here: Convert char to int in C and C++.

  • thank you very much! managed to fix it and now it works. only a week to c++... I'll start learning how to use the debugger right away. – Mor Katz Apr 17 '18 at 19:52
  • 1
    "should be `for (int i = 0; i < Given.length(); i++)`" - *I*'d say it should. be `for (const auto& i : Given)` ... – Jesper Juhl Apr 17 '18 at 20:27