chcek valid palindrome(basic) , buffer overflow , - c++

I am newbie and I have to check valid palindrome string.
Here is my code in c++
char to_lower(char ch){
char c = ch - 'A' + 'a';
return c;
}
bool isPalindrome(string s) {
int l = s.length();
string t = "";
for(int i=0;s[i]!='\0';i++){
if(((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z') || (s[i]>='0' && s[i]<='9')))
t.push_back(s[i]);
if(t[i]>='A' && t[i]<='Z')
t[i] = to_lower(t[i]);
}
int i=0;
int j=t.length()-1;
while(i<=j){
if(t[i]!=t[j])
return false;
else
i++;
j--;
}
return true;
}
It is showing stack buffer overflow. I am not understanding this error is showing. Please help me

Related

Error handling exponent ("e") preceding digit

I'd like to create a function that checks whether a number input with an exponent such as 1.32e2, 1e3, +1.32e+2 indeed has the e in the correct position, after a number, not before it (such as e1 or .e4)
I'm a beginner so it's just trial and error at this point. This is what I have so far:
bool validate_alpha_e(string op) {
if (count_alpha(op) <= 1) {
if (count_es(op) == 1) {
//return true;
int length = op.length();
for (int i = 0; i < length; i++) {
char ch = op[i-1];
if (ch == 'e' || ch == 'E') {
if (i-1 != isdigit(i)) {
return false;
}
}
}
return true;
}
Worked it out. Thanks for the comments but I wasn't able to figure it out.
So I had to create 3 separate functions (see below)
First function validates for correct input before the e.
Second function validates for correct input after the e.
Third function validates that the first character is not an e.
Put all these together in a bool if statement and if it returns false then the input is not correct.
bool validate_e_after(string op) {
int length = op.length();
for (int i = 1; i < length; i++) {
char ch = op[i-1];
if (ch == 'e' || ch == 'E') {
char ch2 = op[i];
if (isdigit(ch2) || ch2 == '+' || ch2 == '-') {
return true;
}
else {
return false;
}
}
}
}
bool validate_e_before(string op) {
int length = op.length();
for (int i = 1; i < length; i++) {
char ch = op[i+1];
if (ch == 'e' || ch == 'E' && i != 0) {
char ch2 = op[i];
if (isdigit(ch2) || ch2 == '+' || ch2 == '-') {
return true;
}
else {
return false;
}
}
}
}
bool validate_ezero(string op) {
int length = op.length();
for (int i = 0; i < length; i++) {
char ch = op[i];
if (ch == 'e' or ch == 'E') {
if (i == 0) {
return false;
}
}
}
return true;

Why this if(s[j]==s[i] && i>0) condition is not work for this [{()}] [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Question link
In this question firstly user will give the number of test cases, for each of the test cases users enter a string like [{()}]. This code if s[i] value equal to any left bracket like '(', '[', '{' then i added it's right bracket into ans string otherwise we have to compare last added character in ans with current s[i] character.
#include <bits/stdc++.h>
using namespace std;
string isBalanced(string s) {
string ans;
int j=-1;
for(int i=0; i<s.length(); i++)
{
if(s[i]=='(' || s[i]=='[' || s[i]=='{')
{
if(s[i]=='(')
ans.push_back((char)(s[i]+1));
else ans.push_back((char)(s[i]+2));
j++;
}
else if(s[j]==s[i] && i>0){
ans.pop_back();
j--;
}
}
if(ans.empty()) return "YES";
else return "NO";
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int t_itr = 0; t_itr < t; t_itr++) {
string s;
getline(cin, s);
string result = isBalanced(s);
fout << result << "\n";
}
fout.close();
return 0;
}
Edit. In your code, I found three issues:
You compare s[i] with s[j], while you should made the comparaison with ans[j]
Before using index j, you should first check it is positive.
As soon as the comparaison fails, you should return "NO".
This is your code, corrected:
string isBalanced_OP(string s) {
string ans;
int j = -1;
for (int i = 0; i < s.length(); i++) {
if (s[i]=='(' || s[i]=='[' || s[i]=='{') {
if (s[i]=='(') ans.push_back ((char)(s[i]+1));
else ans.push_back ((char)(s[i]+2));
j++;
}
else if (j < 0) {
return "NO";
} else if (ans[j]==s[i]){
ans.pop_back();
j--;
} else {
return "NO";
}
}
if(ans.empty()) return "YES";
else return "NO";
}
Another important point is that your algorithm seems too complex for this problem.
If you don't have other characters than brackets, you only need to compare current first and current last characters, and no need for string ans. You can return "NO" as soon as you get a mismatch.
string isBalanced(string s) {
int n = s.size();
if (n%2) return "NO";
int i = 0;
int j = n-1;
while (i < j) {
bool check;
check = (s[i] == '(' && s[j] == ')');
check = check || (s[i] == '[' && s[j] == ']');
check = check || (s[i] == '{' && s[j] == '}');
if (!check) return "NO";
++i;
--j;
}
return "YES";
}
Edit: it appears after my first post that a sequence like ()[]{} is well balanced, which is not so clear from the question on the online site, and not mentioned originally in the question here. Therefore, I now provide this second program, based on a stack. The idea is to stack opening brackets, and to check each close bracket with the last character entered in the stack. It appears finally that this code is rather similar to yours, after correction of your code.
string isBalanced2(string s) {
int n = s.size();
if (n%2) return "NO";
std::stack<char> st;
for (int i = 0; i < n; i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
st.push (s[i]);
continue;
}
if (st.empty()) return "NO";
char mem = st.top();
st.pop();
bool check;
check = (mem == '(' && s[i] == ')');
check = check || (mem == '[' && s[i] == ']');
check = check || (mem == '{' && s[i] == '}');
if (!check) return "NO";
}
if (st.empty()) return "YES";
else return "NO";
}

count the ocurrences of substrings

I've a task to count the occurrences of sub string in a char String. I write this code but on certain inputs output is wrong. like string is "hassana" and sub is "as" then it outputs 2 ...some one plz help me
int CharString :: countOccurenceOf(const char* substr)
{
int count = 0;
bool find = false;
for(int i = 0; i < size1; i++)
{
if(cstr[i] == substr[0])
{
int x = i;
int c = 1;
find = true;
while ( substr[c] != '\0' && find == true && (x+1) < size1)
{
if(cstr [x+1] != substr[c])
{
find = false;
}
c++;
x++;
}
if (find == true)
{
count++;
i = i + c-1;
}
}
}
return count;
}
Got some Solution.....is that okay?
int CharString :: countOccurenceOf(const char* substr)
{
int len = 0;
if ( substr != '\0')
{
while( substr[len] != '\0')
len++;
}
int count = 0;
bool find = false;
for(int i = 0; i < size1; i++)
{
if(cstr[i] == substr[0])
{
int x = i;
int c = 1;
find = true;
while ( substr[c] != '\0' && find == true && (x+1) < size1)
{
if(cstr [x+1] != substr[c])
{
find = false;
}
c++;
x++;
}
if (find == true && c == len)
{
count++;
i = i + c-1;
}
}
}
return count;
}
The problem is that you're breaking automatically if x+1 < size1. If the first character of the substring matches the last character of the main string, then this will automatically break and "find" will still be set to true so you'll increment matches by 1. There are numerous ways to change your code to fix this problem; hopefully you can find one now that you know what the problem is.
Assuming cstr is your class internal string:
int CharString :: countOccurenceOf(const char* substr)
{
int occurrencies = 0;
unsigned char* s = cstr;
while (s) {
if (strstr(s,substr)) { occurrencies++; s+= strlen(substr); }
else s++;
}
return occurrencies;
}

How do I compare the s[] to char vowels?

int main()
{
string s;
//char a[5][8];
getline(cin,s);
int m= s.length();
char a[m][8];
//a == &city[0];
//s
char vowels[]={'a','e','i','o','u'};
for (int i = 0 ; i < m ; ++i)
{
if (s[i] !=*vowels)//, 'e' , 'i' , 'o' , 'u'))
{
s[i] = tolower(s[i]);
}
else //if (s[i]=vowels[5])
{
s[i]=toupper(s[i]);
}
cout << s[i] ;
}
return 0;
}
I am trying make all the vowels in uppercase and all consonents lowecase, but code is not working whats wrong with this?

C++ return negative string

Hi i have the following code to convert string integer into integer, these are the code:
#include <stdio.h>
int str_to_int(char* str) {
int output = 0;
char* p = str;
for (int i=0;str[i]!='\0';i++) {
char c = *p++;
if (c < '0' || c > '9')
continue;
output *= 10;
output += c - '0';
}
return output;
}
int main(){
printf("%d\n", str_to_int("456xy"));
printf("%d\n", str_to_int("32"));
printf("%d\n", str_to_int("-5"));
return 0;
}
But some how printf("%d\n", str_to_int("-5")); some how returning 5 instead -5, where am i wrong here? Thanks
You don't really seem to account for "-" at all in your code.
You should insert some kind of hook to detect if it's a negative value:
#include <stdio.h>
int str_to_int(char* str) {
int output = 0;
char* p = str;
bool isNeg = false;
if (*p == '-')
{
isNeg = true;
p++;
}
for (int i=0;str[i]!='\0';i++) {
char c = *p++;
if (c < '0' || c > '9')
continue;
output *= 10;
output += c - '0';
}
if (isNeg)
{
output *= -1;
}
return output;
}
int main(){
printf("%d\n", str_to_int("456xy"));
printf("%d\n", str_to_int("32"));
printf("%d\n", str_to_int("-5"));
return 0;
}
it's the if (c < '0' || c > '9') continue; that causes this problem.
When variable c is '-', you just simply skip it. So there is no negative sign in your result.
Please just test if this number is negative (has '-') before your whole logic.
In your conversion function, you skip over the - character, because it is not in your tested range:
if (c < '0' || c > '9')
continue;
To fix it, you need to test for the - character, and negate the value after you are done converting the value.
if (c < '0' || c > '9') {
if (c == '-' && no_other_digits_processed_yet) is_neg = true;
continue;
}
//...
if (is_neg) output = -output;
return output;