I have written the following code in c++ 20. The code is facing some problems: Line Col…
- User
I have written the following code in c++ 20. The code is facing some problems: Line Col Message 10 36 extended character ‘ is not valid in an identifier 10 36 ‘‘0’’ was not declared in this scope 10 42 ‘‘1’’ was not declared in this scope Here is the code: #include #include #include
using namespace std;
// Function to toggle the bits from index L to R inclusive void toggle(string &str, int L, int R) { for (int i = L; i <= R; ++i) { str[i - 1] = str[i - 1] == ‘0’ ? ‘1’ : ‘0’; } }
// Function to calculate the value of V(l, r) int V(const string &str, int l, int r) { int k = 1; // At least one index will always exist for (int i = l; i < r; ++i) { if (str[i - 1] != str[i]) { ++k; } } return k; }
// Function to answer the queries of type 2 int query(const string &str, int L, int R) { int sum = 0; for (int l = L; l <= R; ++l) { for (int r = l; r <= R; ++r) { sum += V(str, l, r); } } return sum; }
int main() { int N, Q, type, L, R; string binaryString;
// Input processing cin >> N; cin >> binaryString; cin >> Q; // Query processing for (int i = 0; i < Q; ++i) { cin >> type >> L >> R; if (type == 1) { toggle(binaryString, L, R); } else if (type == 2) { cout << query(binaryString, L, R) << endl; } } return 0;}
- Assistant
The issue with your code stems from using the wrong type of quotes for the character literals. In C++, characters are enclosed in single quotes ('). You've used ‘ (left single quotation mark) and ’ (right single quotation mark) instead of the correct ' (single quote) character.
Here is the corrected line:
str[i - 1] = str[i - 1] == '0' ? '1' : '0';When replacing the incorrect quotes, make sure you replace all occurrences in the code. Here is the correct version of your
togglefunction:// Function to toggle the bits from index L to R inclusive void toggle(string &str, int L, int R) { for (int i = L; i <= R; ++i) { str[i - 1] = str[i - 1] == '0' ? '1' : '0'; } }Ensure you apply this change to all the character literals in the entire code. With that change, your program should compile and run without the errors you were encountering.
- User
But the code is facing these problems: Line Col Message 10 36 extended character ‘ is not valid in an identifier 10 36 ‘‘0’’ was not declared in this scope 10 42 ‘‘1’’ was not declared in this scope 58 6 redefinition of ‘void toggle(std::string&, int, int)’ 60 36 ‘‘0’’ was not declared in this scope 60 42 ‘‘1’’ was not declared in this scope
- Assistant