How to handle floatingbpoint exception? - c++

I was creating a code for rotation of specif number in a string and initially i created it for one user input ! It worked as soon as i added on logic for multiple test case its is showing floating point exception.....
can anyone tell me in the code what caused that error !
#include<iostream>
#include<cstring>
using namespace std;
void stringrot(char str[],int n)
{
int l=strlen(str);
char temp[100];
int k=n%l;
for(int i=0;i<k;i++)
{
temp[i]=str[(l-k+i)];
}
for(int i=0;i<l-k;i++)
{
temp[k+i]=str[i];
}
temp[l]='\0';
cout<<temp;
}
int main()
{
int test;
cin>>test;
while(--test>=0)
{
char str[100];
cin.getline(str,50);
int n;
cin>>n;
stringrot(str,n);
}
}
Here is the code !

Let's take a closer look at the while loop in main
while(--test>=0)
{
char str[100];
cin.getline(str,50);
int n;
cin>>n;
stringrot(str,n);
}
Loop Iteration 1
cin.getline(str,50); << reads a line
cin>>n; << reads an integer. After enter is pressed. Enter
is not an integer. Enter is not read and stays
in the stream
stringrot(str,n);
Loop Iteration 2
cin.getline(str,50); << reads a line. Fortunately there is an enter
still in the stream making it really easy to
find the end of the line. It's the first
character that's going to be read.
cin>>n; << reads an integer. Unfortunately the user
probably thinks they are typing in the string
and doesn't type in a number. Oops.
stringrot(str,n);
Anyway stringrot gets called with stringrot("",0), so the first few lines of stringrot wind up looking like
int l=strlen(""); << l will be zero because the string is emtpy
char temp[100];
int k=n%l; << resolves to 0%0 and an integer divided by zero is BOOM!
Solution:
Change the guts of the while loop to something like
char str[100];
cin.getline(str,50);
int n;
cin>>n;
// discard everything else on the line including the end of line character
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
stringrot(str,n);
Why an integer division results in a floating point error, one that isn't a catchable C++ exception by the way, seems to be mostly historical. More here: Why is this a floating point exception?
Recommendation:
Use std::string not char arrays.

#include<iostream>
#include<cstring>
using namespace std;
//void stringrot(char str[],int n)
void stringrot(string str,int n)
{
//int l=strlen(str);
int l=str.size();
char temp[100];
int k=n%l;
for(int i=0;i<k;i++)
{
temp[i]=str[(l-k+i)];
}
for(int i=0;i<l-k;i++)
{
temp[k+i]=str[i];
}
temp[l]='\0';
cout<<temp;
}
int main()
{
int test;
cin>>test;
while(--test>=0)
{
//char str[100];
//cin.getline(str,50);
string str;
cin>>str;
int n;
cin>>n;
stringrot(str,n);
}
}

Related

I aim to write a program that will count and store the position of the occurence of a string within a character array

The program will count the position where a specific string occurs within a character array and store that position within an array. As an example the string 'has' would be at positions [0,13,25,33] when compared to the string 'hassan is a hassler who hassles hasslers'. Two main character arrays are being used; str[] and sub[]. str being the string from where the occurrence is counted from and sub the string compared. I have attached my idea of the code. Any help is appreciated and as I am still a student and not a pro, I would very much appreciate constructive help rather than comments on how my code and workflow is sloppy. I wish to display the array with all the positions and the program does not display anything other than the return value, which for some reasons is mostly very big numbers.
#include <iostream>
#include <cstring>
using namespace std;
void allPositionsofSub()
{
int nstr;
int nsub;
char str[100]; //i initially wished to use the variable nstr but it wouldnt work with cin.get
char sub[nsub];
cout<<"Enter the string: ";
cin.get(str, 100);
cout<<"Enter the sub: ";
cin>>sub;
int num;
int count;
int count1=0;
int outdisplay[count];
for(int nstr1=0;nstr1<=99;nstr1++)
{
char n;
n = sub[nstr1];
while (nstr1<=nsub)
{
if (n==str[nstr1])
{
outdisplay[num]=nstr1;// this is where i think the problem perhaps lies.
num++;
count++;
}
}
}
while(count1<=count)
{
cout<<outdisplay[count1]<<", ";
count1++;
}
cout<<"-1";
}
int main()
{
allPositionsofSub();
}
updated code:
#include <iostream>
#include <cstring>
using namespace std;
void allPositionsofSub()
{
int nstr;
int nsub=20;
char str[100];
char sub[20];
cout<<"Enter the string: ";
cin.get(str, 100);
cout<<"Enter the sub: ";
cin>>sub;
int num;
int count;
int count1=0;
int outdisplay[count];
for(int nstr1=0;nstr1<=99;nstr1++)
{
char n;
n = sub[nstr1];
if (n==str[nstr1])
{
outdisplay[num]=nstr1;
num++;
count++;
}
}
while(count1<=count)
{
cout<<outdisplay[count1]<<", ";
count1++;
}
cout<<"-1";
}
int main()
{
allPositionsofSub();
}
So the basic idea is to enumerate over every position in the source string and check whether it is the start of your substring.
It is better for you to try implementing the following pseudo-code, and come back if you have any more questions.
# substr_len: The length of the substring you are looking for.
# str_len: The length of the source string.
# result: An array of int with sufficient length.
let match_count = 0
for (i in range 0..str_len-substr_len)
let match = true
for (j in range 0..substr_len-1)
if (substr[j] != str[i + j])
match = false
break
if (match)
result[match_count] = i
match_count = match_count + 1

Why this code doesn't allow me to receive the whole array?

#include <bits/stdc++.h>
using namespace std;
string bin(int n){
string x="";
while(n!=0)
{
int z=n%2;
x+=to_string(z);
n%=2;
}
return x;
}
int main(){
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
string x=bin(a[i]);
int u=x.size();
int cnt=0;
for(int g=0;g<u;g++)
{
if(x[g]=='1')
++cnt;
}
cout<<cnt<<' ';
}
cout<<'\n';
}
}
This code is given several test cases and each test case will have an array of n integers, for each element in the array I should count the number of ones in the binary representation of it. I wrote a function that expects an integer and returns a string containing the binary representation of it. But I wonder why my code does not end, and not allowing me to receive other numbers in array.
For instance, there's one test case and and only array of 2 integers if I inputted 1 and wait for ever to enter the second number, what's happening?
This is your bin function reduced to the bare minimum:
string bin(int n){
while(n!=0)
{
n%=2;
}
return {};
}
If n is even you will set it to 0 on the first iteration, otherwise you set it to 1 and never change it afterwards (1%2==1). Hence you have a endless loop. I won't spoil you the "fun" of completing the exercise, so I will just point you to using a debugger. If you step trough your code line by line you could have observed how n never changes and why the loop wont stop.
PS: (spoiler-alert) you might want to take a look at std::bitset (end of spoiler)

Why this different behaviour while indexing the array using character?

I am trying to write a c++ program to find the first non-repeated character and if all the characters are repeated it would return -1.
I have designed a solution that keeps track of the count of characters using a integer array which I index using the respective character whose count has to be stored.
Program 1:
Gives erroneous output...
http://ide.geeksforgeeks.org/wxOYog
#include<iostream>
#include<cstring>
using namespace std;
int map[256];
string returnFirstRepeatingChar(string str,int n)
{
int i=0,flag=1;
string result;
for(i=0;i<n;i++)
map[str[i]]++;
for(i=0;i<n;i++)
{
if(map[str[i]]==1)
{
flag=0;
result = str[i];
break;
}
}
if(flag)
return "-1";
else
return result;
}
int main()
{
//code
int t,N,*arr,i,j;
cin>>t;
string str;
while(t--)
{
cin>>N;
memset(&map,0,256);
cin>>str;
cout<<returnFirstRepeatingChar(str,N)<<endl;
}
return 0;
}
Program 2:
Gives correct output...
http://ide.geeksforgeeks.org/jJvJPu
#include<iostream>
#include<cstring>
using namespace std;
int map[256];
string returnFirstRepeatingChar(string str,int n)
{
int i=0,flag=1;
string result;
for(i=0;i<n;i++)
map[str[i]-97]++; //changed from above program
for(i=0;i<n;i++)
{
if(map[str[i]-97]==1) //changed from above program
{
flag=0;
result = str[i];
break;
}
}
if(flag)
return "-1";
else
return result;
}
int main()
{
//code
int t,N,*arr,i,j;
cin>>t;
string str;
while(t--)
{
cin>>N;
memset(&map,0,256);
cin>>str;
cout<<returnFirstRepeatingChar(str,N)<<endl;
}
return 0;
}
Only difference between the two programs is location of required counts in the array map..
In the program 1, it starts from 97 (ascii of a)
In the program 2, it starts from 0.
But program 2 gives correct output, but the program 1 isn't. Why?
Eg: for input: abcdefghij
program 1 output: f
program 2 output: a
One important issue here is this line:
memset(&map,0,256);
Here you are zeroing only the first 256/sizeof(int). In case the sizeof(int) is 4, this makes the first 64 int.
However, your program is using the elements which index is greater than 97, hence the issue appearing.
Hence it should be
memset(&map,0,256*sizeof(int));
or could be also simply written as
memset(map,0,sizeof(map));
Remember: the 3rd parameter of memset is "the number of bytes to fill", not "the number of elements of your array"

Why is the loop terminating just after a single execution?

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
int n;
cin>>n;
int x=0;
while(n--)
{
char s[3];
cin>>s;
if(strcmp(s,"X++")==0||strcmp(s,"++X")==0)
x+=1;
else
x-=1;
}
cout<<x;
}
The loop worked fine when I removed the strcmp line inside the if statement.
Like πάντα ῥεῖ said, the size of s must be 4 in order to store the '\0' character. Otherwise :
cin >> s; // For example write "X++"
will store your string in s and put '\0' out of the bounds of s.
When the program goes in the loop for the second time, you won't be able to write it because it will get "" (an empty string) every time.
To fix that, just replace 3 with 4 and that will be OK.
Note : If you really want to use C++, I suggest you to use std::string.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int n;
cin >> n;
int x = 0;
while(n--)
{
string s;
cin >> s;
if(s == "X++" || s == "++X")
x+=1;
else
x-=1;
}
cout << x;
return 0;
}

Unexpected results converting decimal number to binary

# include <iostream>
# include <cmath>
using namespace std;
int main()
{
int p;
int n;
int q;
cin>>n;
int r;
r=0;
for (int i=0,n; n>1; i=i+1,n=n/2)
{
p=n%2;
q= p*(pow(10,i));
r=r + q;
}
cout<<r;
system("pause");
return 0;
}
I am not supposed to use arrays. It compiles fine but when executed and a number is entered, it doesn't produce the desired results.
For instance, when 22 is entered, it gives -2147483648 whereas the desired output would be 10110.
your way is limited and not effient in converting to binary
you should use string it's more helpful and the range is big enough for any number
this is my code for decimal-to-binary
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
long long n;
string s,bin;
stack<string> res;
cin>>n;
while(n>0)
{
if(n%2==0)
s='0';
else
s='1';
res.push(s);
n=n/2;
}
while(!res.empty())
{
bin=bin+res.top();
res.pop();
}
cout<<bin<<endl;
return 0;
}
I hope it will help you.
int i=0,n;
should be
int i=0;
I don't know what you thought you were doing there, but what you are actually doing is declaring another variable n. Because the second n variable doesn't have a value the rest of the code doesn't work.
That's not the only problem with your code, but I'm sure you can figure out the rest.