In my code I did this
int y=strcmp(s,s1);//before this I converted all the uppercase of the string input as lower case.
if(y==0)
{
cout<<"0"<<endl;
}
else if(y >= 1)
{
cout<<"1"<<endl;
}
else if(y<1)
{
cout<<"-1"<<endl;//problem was here
}
so i took aaaa and aaaA as input and expected 0 as output . But it gave me -1 as output.
But in my code when I wrote this:
int y=strcmp(s,s1);
if(y==0)
{
cout<<0<<endl;
}
else if(y >= 1)
{
cout<<1<<endl;
}
else if(y<1)
{
cout<<-1<<endl;
}
It gave me the right answer.
My question why this happened?
you removed " " in the cout. Can you show the error code you're getting in the first round?
Related
I was trying to solve lapindrome problem on codechef.
On my local ide the program ran as expected.
But while in codechef submission it is giving runtime error "SIGCONT".
#include<iostream>
#pragma GCC optimize("Ofast")
using namespace std;
int main() {
int t;
cin>>t;
do
{
string l;
cin>>l;
int c = 0;
for (int i = 0; i < (l.length()/2); i++)
{
if (l[i] == l[i+(l.length()/2)])
{
c++;
}
}
if (c == l.length()/2) {
printf("YES\n");
}
else
{
printf("NO\n");
}
t--;
} while (t!=0);
return 0;
}
First thing I would like to point out that your code is wrong because for the test case rotor your code is giving NO as an answer, it should be YES.
Why getting the wrong answer?
In question it is given, if there are odd number of characters in the string, we ignore the middle character and check for lapindrome.
So, you need to modify/delete the below code.
if (c == l.length()/2) {
printf("YES\n");
}
else
{
printf("NO\n");
}
and instead do this:
if (c == l.length()/2) {
//check for lapindrome
}
else
{
//remove middle character
//check for lapindrome
}
Why "SIGCONT" error?
This error occurs when you exceed the IDE's printing limit. For Codechef IDE, it’s around 2^16 Characters.
You can try printing the output directly in a file locally. (Thanks to black_truce for this).
My Code:
You can check below solution for reference.
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
string str,str1,str2;
cin>>str;
int len=str.length();
if(len%2==0){
str1=str.substr(0, len/2);
str2=str.substr(len/2, len);
}
else{
str1=str.substr(0, len/2);
str2=str.substr(len/2+1, len);
}
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
if(str1==str2) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
Can someone please point out the reason for the segmentation fault in my code. I am trying to convert an arithmetic expression with precedence decided by '()' into postfix form and then solve the expression.
#include<iostream>
#include<string>
#include<stack>
using namespace std;
string post(string exp)
{
cout<<"reached post";
stack<char> s2;
string new_exp="";
int length=exp.length();
for(int i=0; i<length; i++)
{
if(exp[i]=='(')
{
s2.push(exp[i]);
}
else if(exp[i]=='+'|| exp[i]=='-' || exp[i]=='*' || exp[i]=='/')
{
new_exp+=' ';
s2.push(exp[i]);
}
else if(exp[i]>='0'&& exp[i]<='9')
{
new_exp+=exp[i];
}
else if(exp[i]==')')
{
new_exp+=' ';
new_exp+=s2.top();
s2.pop();
s2.pop();
}
}
if(!s2.empty())
{
while(!s2.empty())
{
new_exp+=' ';
new_exp+=s2.top();
s2.pop();
}
}
return(new_exp);
}
int operation(char op, char op1, char op2)
{
if(op == '+') return(op1+op2);
else if(op=='-') return(op1-op2);
else if(op=='*') return(op1*op2);
else if(op=='/') return(op1/op2);
}
int solve(string expression)
{
cout<<"\nreached solve";
string postfix=post(expression);
stack<char> s;
int res;
int length=postfix.length();
for(int i=0; i<length; i++)
{
if(postfix[i]==' ')
{
continue;
}
else if(postfix[i]=='+'|| postfix[i]=='-' || postfix[i]=='*' || postfix[i]=='/')
{
char op2=s.top();
s.pop();
char op1=s.top();
s.pop();
res=operation(postfix[i],op1,op2);
s.push(res);
}
else if(postfix[i]>='0' && postfix[i]<=9)
{
int operand=0;
while(postfix[i]!=' ' || i!=length)
{
operand=(operand*10)+(postfix[i]-'0');
i++;
}
i--;
s.push(operand);
}
}
return(res);
}
int main(void)
{
string exp;
int result;
cout<<"Enter expression: ";
getline(cin,exp);
result=solve(exp);
cout<<"\nResult= "<<result;
return 0;
}
I get the following error message:
cav#cav-VirtualBox:~/src/cpp$ ./infix_postfix
Enter expression: 10+3
Segmentation fault (core dumped)
I can see at least two mistakes. First,
else if(postfix[i]>='0' && postfix[i]<=9)
You need to compare character '9', not integer 9 as you have a string here. It should be:
else if(postfix[i]>='0' && postfix[i]<='9')
^ ^
Second problem is here:
while(postfix[i]!=' ' || i!=length)
You meant and operation && here, not or ||. When it's a || it is basically true for all characters except i runs out of the length. Also i != length should be tested before postfix[i] != ' ' since when i == length postfix[i] will be out of bound. This line should be:
while(i!=length && postfix[i]!=' ')
Due to these two mistakes you are not pushing values to your stack correctly, getting erronous values at different times which is leading to segmentation fault.
I can't get the right output.. please help me..
and it should return false when I put number as the first character for the name
like this ,
Enter the name of the first rectangle: rec 1a
Invalid input. Type 'rec' following by the name or 'stop' if done.
Try again! Enter the name of the first rectangle: rec a
Enter a's bottom left x and y coords: 9 3
Enter a's length and height: 2 8
i am only allow to use these 3, not anything else..
#include <iostream>
#include <string>
#include <vector>
and my code is
bool promptread_rec(const string & prompt, const string & invalid, const string & usedname, string & input, vector<Rectangle> & list)
{
cout << prompt;
getline(cin, input);
if (input == "stop")
{
return true;
}
else if (input.substr(0,4) != "rec ")
{
cout << invalid << endl;
return false;
}
else if (input[4] == '0' || input [4] == '1' || ......)
{
cout << invalid << endl;
return false;
}
else if (list.size() > 0)
{
for (int i = 0; i < list.size(); i++)
{
if (input == list[i].getName())
{
cout << usedname;
return false;
}
}
return true;
}
else
{
return true;
}
}
is there a faster way to do it?? need to avoid all numbers e.g. 0,1,2,3,...,9
From the header cctype, you may use the function isalpha(c) on the first character of the string, like:
string a = "a1234";
assert(isalpha(a.at(0)) == true);
a = "1234";
assert(isalpha(a.at(0)) == true);
Just remember to access a.at(0) only if the string is not empty or else it will throw a std::out_of_range exception
References:
http://www.cplusplus.com/reference/cctype/isalpha/
http://www.cplusplus.com/reference/cassert/assert/
http://www.cplusplus.com/reference/string/string/at/
Since you cannot use any other headers you have to implement your own functions, which is actually simple enough for ASCII characters:
bool IsLetter(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
bool IsDigit(char c) {
return c >= '0' && c <= '9';
}
Using these two helper functions you can write a function to test if a name is valid:
bool IsValidName(const std::string &name);
I leave this for you to implement.
I've been toying with this c program for a while, and I can't seem to figure out what I'm missing.
In the very bottom of my code, I have a function that replaces every other word with a "-".
My problem is that when I enter an odd numbered word, such as "Cat", "dog", "hamburger", it will place a "-" in what I think is the null character position, though I have not been able to debunk it.
Thank you for your help!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void replace(char w[]);
int main( )
{
char w[100], x[100], y[100];
int z = 0;
printf("Player 1, please enter the secret word: ");
fgets(x,100,stdin);
// system("clear");
while( strcmp(x,y) != 0 )
{
strcpy(w,x);
// printf("\nLength of String : %d", strlen(w)-1);
replace(w);
printf("Player 2, the word is %s\n",w);
printf("Player 2, please guess the word: ");
fgets(y,100,stdin);
z++;
if( strcmp(x,y) != 0 )
{
printf("Wrong. Try again.\n");
}
else
{
//system("clear");
printf("Correct!\n");
printf("It took you %d attempt(s).\n",z);
switch (z)
{
case 1 :
case 2 :
printf("A. Awesome work!");
{break;}
case 3 :
case 4 :
printf("B. Best, that was!");
{break;}
case 5 :
case 6 :
printf("C. Concentrate next time!");
{break;}
case 7 :
printf("D. Don't quit your day job.");
{break;}
default :
printf("F. Failure.");
{break;}
}
}
}
getch();
}
void replace(char w[])
{
int a;
a = 0;
while (w[a] != '\0')
{
if (a % 2 != 0)
{
w[a] = '-';
a++;
}
if (w[a] != '\0')
{
a++;
}
else
{
break;
}
}
}
From the fgets manual;
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (\0) is stored after the last character in the buffer.
The newline entered is what you're replacing.
You can implement like this...
int a;
int len;
a = 0;
len = strlen(w);
if(len%2 == 0)
len = len-1;
while (len!=a)
{
if (a % 2 != 0)
{
w[a] = '-';
a++;
}
if (w[a] != '\0')
{
a++;
}
else
{
break;
}
}
I think replacing fgets with just gets will work:
Try:
//fgets(x,100,stdin);
gets(x);
and
//fgets(y,100,stdin);
gets(y);
That will be enough I think.
The problem is caused by the additional '\n' character in the char array passed to the replace function.
For instance, when the input is "Cat", the passed char[] w contains {'C', 'a', 't', '\n', '\0'};
The additional '\n' also gets replaced with "-" character.
The following will solve this problem.
while (w[a] != '\0')
{
if (w[a] != '\0' && w[a] != '\n')
{
if (a % 2 != 0)
{
w[a] = '-';
}
a++;
}
else
{
break;
}
}
As a bit of an aside, can I suggest structuring your replace() code differently
void replace(char charw[])
{
int length=strlen(charw);
int i;
for (i=0;i<length;i++)
{
if (i%2==1) /*yes, i%2 would also work, but lets not get too clever*/
{charw[i]='-';}
}
}
This is far more readable. Breaking in the middle of a loop...not so much.
I have the following code and I have defined the functions that I am calling here, the problem here is : I run the code
input: 1
input: 2
input: 2
input: 6
input: 5 6 // for the scanf associated with i=6;
after this I get the output on the screen as
enter ur choice and then it exits out of the program ... its like the scanf gets the value from somewhere but I dunno from where I also tried fflush(stdin) doesnt seem to work can any one please help
int main()
{
int i,*j,k,pos,val;
Element *stacka = new Element;
stacka =NULL;
while(i!=5)
{
printf("Enter ur choice \n");
fflush(stdin);
scanf("%d",&i);
if(i==1)
{
if(createStack(&stacka))
{
printf("yes");
}
}
if(i==2)
{
k=2;
if(push(&stacka,&j))
{
printf("yes");
}
}
if(i==3)
{
if(pop(&stacka,&k))
{
printf("yes %d",k);
}
}
if(i==4)
{
if(emptyStack(&stacka))
{
printf("yes");
}
}
if(i==6)
{
scanf("%d,%d",&pos,&val);
fflush(stdin);
insert_at_pos(pos,val,&stacka);
}
}
return 0;
}
Try inserting a space before %d:
scanf(" %d,%d",&pos,&val);
This will eat any leading whitespace that might be in the input buffer, e.g., the newline from the earlier entry of i.
Also, initialize i before the loop.