Runtime Error

[question]
I am in a C++ class working on a challenge activity using the find() command. I am having a hard time figuring out how to correct my code and prevent the error message
"Runtime error (commonly due to an invalid array/vector access, divide by 0, etc.).
Tests aborted." from coming up.
The challenge activity doesn't give any hints as to help solve the task, but the directions given are as follows...
"Print 'Censored' if userInput contains the word 'darn', else print userInput. End with newline."
No new variables can be created and only the code inside the two comments(// My answer) can be edited.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
using namespace std;

int main() {
   string userInput;

   userInput = "That darn cat.";

// my answer START
    userInput.find('d');
     if (userInput.substr(userInput.find('d'), 4) == "darn") {
       std::cout << "Censored" << std::endl;
     }
     else{
       std::cout << userInput << std::endl;
     }
// my answer END

   return 0;
}

Last edited on
Following http://www.cplusplus.com/reference/string/string/find/
I made this...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int main() {
    string userInput;
    userInput = "That darn cat.";

// my answer START
    if (userInput.find ("darn") != std::string::npos) {
        cout << "Censorded" << endl;
    } else {
        cout << userInput << endl;
    }
// my answer END

    return 0;

}



I am not sure what is wrong with your code.
I copied your code and it runs just fine. I even copied and pasted another if routine with a different result, and that ran fine as well...

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
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

int main() {
   string userInput;

   userInput = "That darn cat.";

// my answer START
    userInput.find('d');
     if (userInput.substr(userInput.find('d'), 4) == "darn") {
       std::cout << "Censored" << std::endl;
     }
     else{
       std::cout << userInput << std::endl;
     }

     userInput = "That dang cat.";

     if (userInput.substr(userInput.find('d'), 4) == "darn") {
       std::cout << "Better language" << std::endl;
     }
     else{
       std::cout << userInput << std::endl;
     }
// my answer END

   return 0;
}
Topic archived. No new replies allowed.