wrong output in strings - c++

My program calculates the length of each word before space and compares it with a fixed number.
The number is chosen from another string (pi).
I don't know why but my variable FLAG is always set to false so I always get the same output.
I don't know where the problem is. Please help out
#include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <algorithm>
#include <iomanip>
using namespace std;
int main() {
int t=0,num;
int i,j,len,space;
bool FLAG;
string pi ="31415926535897932384626433833",song;
cin>>t;
while(t--){
len=0,space=0,i=0,j=0,num=0,FLAG=true;
cin.ignore();
getline(cin,song);
// problem from here
while(1) {
i=0,num=0,FLAG=true;
len=song.length();
space=song.find(' ');
if(space==-1){
if(len==pi[j]){
FLAG=true;
break;
}
else{
FLAG=false;
break;
}
}
else{
while(i<space){
num++;
i++;
}
if(num==pi[j]){
FLAG=true;
j++;
num=0;
i=0;
song.erase(0,space+1);
cout<<song<<endl;
}
else{
FLAG=false;
break;
}
}
}
// to here
if(FLAG==true){
cout<<"It's a pi song."<<"\n";
}
else{
cout<<"It's not a pi song."<<"\n";
}
}
return 0;
}

You are comparing an integer with a character value. i.e. you are comparing 3 with '3'. To get a number from a character digit, subtract '0'.
So you could write
if (len==(pi[j] - '0'))
Also, please learn to use a debugger, you can step through your code to find the line that doesn't work.

Related

Segmentation error while using stacks in c++ stl?

I was trying to write this code for converting infix expression to postfix expression but I'm getting a segmentation fault for some values. Code is :
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
#include <bits/stdc++.h>
using namespace std;
int prec(char ch){
if(ch=='^')
return 3;
else if(ch=='*' || ch=='/')
return 2;
else if(ch=='+' || ch=='-')
return 1;
else
return 0;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
stack <char> st;
string s;
cin>>s;
for(int i=0;i<21;i++){
if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z'))
cout<<s[i];
else{
if( st.empty())
st.push(s[i]);
else if( s[i]=='(' || prec (s[i])> prec(st.top()))
st.push(s[i]);
else if( s[i]==')'){
while(st.top()!='(')
{cout<<st.top(); st.pop();}
st.pop();
}
else{
while(prec(st.top())>=prec(s[i]))
{
cout<<st.top(); st.pop();
}
}
}
}
return 0;
}
For smaller expressions, it gives an answer but for an expression like a+b*(c^d-e)^(f+g*h)-i it gives segmentation fault.
Firstly, the iteration should be just in the strings.
This means that
for(int i=0;i<21;i++){
should be
for(int i=0;i<s.size();i++){
Secondly, you forgot to check if the stack is empty in the loop.
This means that
while(prec(st.top())>=prec(s[i]))
should be
while(!st.empty() && prec(st.top())>=prec(s[i]))

C++ Verify if string 1 exist in string 2

Help me please !!
it doesn't work and i didn't founf the mistake !?
there is a function to verify existence of strings in each other ?
Thank You !!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string mot1="abc";
string mot2="oooooabcooo";
int j=1;
while((j!=mot1.length())||(j!=0))
{
for(int i=0;i<=mot.length();i++)
{
if(mot1[i]==mot2[i])
{j++;}
else j=0;
}
}
if(j==mot1.length())
cout<<mot1<<" existe dans "<<mot2<<endl;
else
if(j=0)
cout<<"erreur";
return 0;
}
Here is the function you are looking for.
mot2.find(mot1); // also std::find
Hope this helps.
There are out of box tools for this, but if you look for a labor coding, I understand nothing from your code. Instead, I find it this way:
#include <iostream>
#include <string>
using namespace std;
int find(string mot1,string mot2)
{
bool found;
for(int j=0;j<mot2.length()-mot1.length()+1;j++)
{
found=true;
cout<<"comparing "<<mot1.c_str()<<" and "<<(mot2.c_str()+j)<<endl;
for(int i=0;i<mot1.length();i++)
if(mot1[i]!=mot2[i+j])
{
found=false;
break;
}
if(found)
return j;
}
return -1;
}
int main()
{
string mot1="abc";
string mot2="oooooabcooo";
cout<<find(mot1,mot2)<<endl;
return 0;
}

Reading arrays from binary file C++

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>
using namespace std;
int main()
{
srand(time(0));
const int array_size=10,n=10;
int i,j,k;
fstream io("io.dat", ios_base::binary);
float a[array_size];
for (i=0;i<n;i++) {
cout<<"Inputting "<<i+1<<" array:\n";
for (j=0;j<array_size;j++) {
a[j]=(float)rand()/(RAND_MAX+1)*200-100;
cout<<i+1<<"["<<j<<"]="<<a[j]<<endl;
}
io.write((char *)&a,sizeof(a));
}
io.close();
io.open("io.dat", ios_base::binary);
j=1;
while (!io.eof()) {
cout<<"Reading "<<j<<" array:"<<endl;
io.read((char *)&a,sizeof(a));
for (i=0,k=0;i<array_size;i++) {
cout<<j<<"["<<i<<"]="<<a[i]<<endl;
if (a[i]<0) k++;
}
cout<<"Number of negative elements in "<<j++<<" array="<<k<<endl;
}
return 0;
}
I am stuck in reading arrays from binary file. The problem is that condition of breaking reading cycle doesn't even works. Program reads the same array again and again.
This sort of a problem is caused because you are using !in.eof(). One of the easiest way to solve this is to read inside the while loop like in this code
io.open("io.dat", ios_base::binary);
j=1;
while ( io.read( (char *) &a, sizeof(a) ) ) // changed the !in.eof
{
cout<<"Reading "<<j<<" array:"<<endl;
// Removed the read form here
for (i=0,k=0;i<array_size;i++)
{
cout<<j<<"["<<i<<"]="<<a[i]<<endl;
if (a[i]<0) k++;
}
cout<<"Number of negative elements in "<<j++<<" array="<<k<<endl;
}
Well, that should solve the problem with your output.

why getline() need to press enter twice?

My code is
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main(void)
{
int n0,n1,n2;
int move = 0;
long unsigned int arr[3][3];
string str;
char color[4]={'B','G','C','\0'};
char col[40];
while( getline(cin,str))
{
if(str[0]=='\0')continue;
int temp=0,n=0;
int i=0,j=0,k=0;
do{ if(str[k]!=' ')temp=temp*10+(str[k]-48);
else {
if(temp==0) {k++;continue;
}
arr[i][j]=temp;
temp=0;
j++;
if(j==3){j=0;i++;}}
k++;
if(str[k]=='\0' && str[k-1]!=' ')arr[i][j]=temp;
}while(str[k]!='\0');
str[0]='\0'; move = 0;
for(;n!=3;n++)
{
for(j=0,k=0;j<3;j++)
{
temp=0;
if(j==n)continue;
if((j+1)%3==n)k=(j+2)%3;
else k=(j+1)%3;
temp= arr[1][n]+ arr[2][n]+arr[0][j]+ arr[2][j]+arr[0][k]+ arr[1][k]; //total movement
if(n==0 && move==0){move = temp;
n0=n,n1=j,n2=k;}
else if(move>temp){move = temp;
n0=n,n1=j,n2=k;}
else if(move == temp){ if(color[n0]>color[n]){n0=n,n1=j,n2=k;}
else if (color[n0]==color[n] && color[n1]>color[j]){n0=n,n1=j,n2=k;}
}
}
}
col[0]=color[n0],col[1]=color[n1],col[2]=color[n2],col[3]=' ',col[4]='\0';
cout<<col<<move;
}
return 0;
}
here when I enter a string and press Enter, courser only goes to the new line but code does not go forward. I have to press Enter twice to continue the program running. but it should work with one enter.
what is the problem here?
I just tried running your code. It works fine only need to input one time. This is what I ran on my compiler.
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
int n0,n1,n2;
int move = 0;
long unsigned int arr[3][3];
string str;
char color[4]={'B','G','C','\0'};
char col[40];
while( getline(cin,str) )
{
cout<<"hello";
}
return 0;
}
OUTPUT
OUTPUT 2
OUTPUT 3

Testing if a string is a number or character [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to determine if a string is a number with C++?
I have written a very simple calculator program in C++. Here it is:
#include <iostream>
#include <string>
using namespace std;
int main()
{
double num1;
double num2;
string op;
double num3;
int x;
bool y = false;
do
{
cout<<"Press t to terminate the application"<<endl;
cout<<"Enter the first number"<<endl;
cin>>num1;
cout<<"Enter the operator"<<endl;
cin>>op;
cout<<"Enter the next number"<<endl;
cin>>num2;
if(op=="/"&&num2==0)
{
cout<<"You are attempting to divide by 0. This is impossible and causes the destruction of the universe. However, the answer is infinity"<<endl;
y = true;
}
if(y==false)
{
if(op=="+") {
num3 = num1+num2;
}
else if(op=="-") {
num3 = num1-num2;
}
else if(op=="*"||op=="x"||op=="X") {
num3 = num1*num2;
}
else {
num3 = num1/num2;
}
cout<<endl;
cout<<endl;
cout<<"Answer:"<<num3<<endl<<endl;
}
} while(x!=12);
return 0;
}
As you can see, I want to allow people to terminate the application by pressing 't'. This obviously won't work because cin will try and assign a letter to a double (if I do press 't' the application crashes). I am planning to use strings instead to get the input, but how would I test if the string is a letter or a number?
#include <cctype>
and use isalhpa(), isdigit(), isalnum() on string contents?
Here is sample and working code, just change it so it suits your needs
#include <iostream>
#include <string>
#include <cctype>
#include <stdlib.h>
using namespace std;
bool isNum(char *s) {
int i = 0, flag;
while(s[i]){
//if there is a letter in a string then string is not a number
if(isalpha(s[i])){
flag = 0;
break;
}
else flag = 1;
i++;
}
if (flag == 1) return true;
else return false;
}
int main(){
char stingnum1[80], stringnum2[80];
double doublenum1, doublenum2;
cin>>stingnum1>>stringnum2;
if(isNum(stingnum1) && isNum(stringnum2)){
doublenum1 = atof(stingnum1);
doublenum2 = atof(stringnum2);
cout<<doublenum1 + doublenum2 << endl;
}
else cout<<"error";
return 0;
}
You can input into a string, and then use the following function:
int atoi ( const char * str );
If the string is numerical it will translate it into an integer.
If the string isn't numerical it will return 0: in which case you can check only the first character of the string, if its a zero then consider the input as a 0. If the first character isn't a zero consider the string as not numeric.
Well if you only check for 't' you can do it stupid and easy way.
if(stringnum1== 't' || stringnum2== 't') {
//terminate
}
else {
doublenum1 = atof(stringnum1)
doublenum2 = atof(stringnum1)
// your math operations
}
Better way would be:
if(isalhpa(stringnum1) || isalpha(stringnum2)){
//terminate
}
else {
doublenum1 = atof(stringnum1)
doublenum2 = atof(stringnum2)
// your math operations
}
P.S.
if you want to test string and not char, here is sample: link the best way would be to make function to test if given string is number or not if it is number return true, else return false (or other way around)