I am trying to figure out the reason for false output. It works absolutely fine for all values from 0 to 10000 except for values ppp, pppp, qqq and qqqq. The output should be -3,-4,3 and 4 respectively. But on executing this code the output is -5,-5,5 and 6 respectively. Can anyone help me out in this ?
#include<iostream>
using namespace std;
int main()
{
string a;
int x=0;
cin>>a;
for(int i=0;i<10000;i++)
{
if(a[i]=='p')
x=x-1;
if(a[i]=='q')
x=x+1;
}
cout<<x<<endl;
return 0;
}
Thanks in advance.
Your code has undefined behavior unless you enter a string at least 10,000 characters long. The only element outside the string that you're allowed to access is a[a.size()], which returns a null character ('\0'). Anything beyond that is undefined.
Change your loop to:
size_t len = a.size();
for (int i = 0; i < len; i++)
so you don't go outside the string.
Related
#include<iostream>
#include<string.h>
using namespace std;
int main() {
int n;
cin>>n;
char code[n];
cin.ignore();
cin.getline(code, n);
int j=0;
for(int i=0; i<n; i++) {
if((code[i]>='A' && code[i]<='Z') || (code[i]>='a' && code[i]<='z')) {
code[j] = code[i];
j++;
}
}
code[j] = '\0';
cout<<code;
return 0;
}
input :
10
Ajith##
Expected output :
Ajith
Acutal output I'm getting :
Ajithi
why I am getting i at end of array ?
I need to print only alphabets ignoring numbers and special symbols. please help me on this
You tell the program that the input will be ten characters, including null-terminator.
Then you input only seven characters. With the null-terminator that leaves two uninitialized elements of the array, and those two elements will have indeterminate values.
Your loop still uses all ten characters, and using indeterminate values in any way leads to undefined behavior.
What is likely happening is that there's some data after the null-terminator that your program believes is characters.
The solution is std::string and only iterating over the actual length of the string, copying to another std::string.
1.Palindrome code using strings
#include<iostream>
using namespace std;
int main()
{
int t,n;
cin>>t;
while(t--)
{
cin>>n;
string num=to_string(n);
string rev;
//Reversed the string using for loop
for(int i=num.length();i>=0;i--)
{
rev+=num[i];
}
//Checking the strings if they are same
cout<<num<<" "<<rev<<endl;
if(num.compare(rev)==0)
cout<<"wins";
else
cout<<"loses";
}
return 0;
}
2.Output for n=101
101 101
loses
I tried to string method on a separate integer and compare it with other string and it worked.
I don't understand why is the compare method not returning 0.
You access num out of bounds since i = num.length() points at one character passed the last character in the string. It therefore access the terminating \0 character and that's the first character you'll copy and that's why the strings won't match.
Possible correction:
for(size_t i = num.length(); i--;) {
rev += num[i];
}
An alternative, less error prone, solution would be to create rev by using reverse iterators from num:
std::string rev(num.rbegin(), num.rend());
I wrote a simple program to find the longest sub-string with distinct characters in a given string in C++. My code works for certain inputs, but doesn't for others. Moreover, it gives me different outputs for the same inputs. Where am I going wrong?
int main() {
int t;
cin >>t;
while(t--){
string s;
cin >> s;
int n = s.length();
int maxlen = 0;
for(int i = 0; i < n; i++){
int count = 0;
int arr[26] = {0};
bool isDist = true;
int j = i;
while(isDist){
if(arr[(int)s[j] - (int)'a'] == 0){
count++;
arr[(int)s[j] - (int)'a'] = 1;
j++;
} else {
isDist = false;
}
}
if(count > maxlen) maxlen = count;
}
cout << maxlen << endl;
}
return 0;
}
for the following input:
3
aewergrththy
aewergrththy
aewergrththy
My code outputs:
5
4
4
Any help is appreciated, Thank you!
The problem is that there is no check that j remains less than n, so you start checking characters beyond the end of your string, leading to in unpredictable results. Try
while (isDist && j < n)
That should help but I haven't checked the rest of your code for errors.
You could also consider using s.at(j) instead of s[j]. That at least results in predictable behaviour when going out of bounds, at throws an exception in that case.
The program has undefined behavior because you do not bounds-test when iterating over the string with j. You should modify the inner loop to test for j in addition to isDist:
while(isDist && j < n)
Without this, it's very easy for j to shoot past the end of the string as soon as all remaining characters in the string have not yet been encountered.
In this case, it will be when you process the character 'y' at the end of the string. After dealing with 'y', you'll advance j such that s[j] returns the string terminator. Now, you'll be accessing the array with arr[0 - 'y'] which of course is undefined behavior due to being a negative index.
This is the definition of strlen i have goggled up.
strlen( ) function counts the number of characters in a given string and returns the integer value. It stops counting the character when null character is found.
Now according to me the strlen for "kshitij" should be = 7 i.e not including the null character because the function stops counting as and when it encounters the null character.
Therefore if I want to print the word "kshitij" and its reverse as many times as the letters in the word, then the correct code should be.
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char a[1000];
gets(a);
int len=strlen(a);
for(int i=0; i<= len ; i++)
{
for(int j=len ; j>=0; j--)
{
cout<<a[j];
}
cout<<" ";
}
getch();
return 0;
}
accordingly it provides the reasonably correct output.(Apart of spacing I don’t understand)
now I was curious to know what would it print if i did :
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char a[1000];
gets(a);
int len=strlen(a);
for(int i=0; i<= len ; i++)
{
for(int j=len -1 ; j>=0; j--)
{
cout<<a[j];
}
cout<<" ";
}
getch();
return 0;
}
which according to me should not produce the last letter which is "j" but what i see is that it produces the same output but 1 less spacing then before.
similarly i tried :
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char a[1000];
gets(a);
int len=strlen(a);
for(int i=0; i<= len - 1 ; i++)
{
for(int j=len ; j>=0; j--)
{
cout<<a[j];
}
cout<<" ";
}
getch();
return 0;
}
over here according to me the ouput should contain only " 7 - 1 = 6 " times the reverse string but the ouput almost the same.The -1 has no effect on the value of "len".
With all this on my plate , I feel that the strlen function must count the null character as well, wiz strlen (a)= 8 (including ‘\0’), but then I see only 7 outputs in the output window.
This leaves me wondering if the strlen function counts the null character as well or not, and if it does then it must show it as a space in the output window. I am unable to apprehend the complete concept, any help is appreciated?
I am new to programming please take it easy on me. Thanks :).
If you have a string with 7 characters, the array indexes of the printable characters go from 0 to 6, and strlen() will return 7. a[7] contains the null terminator character.
So if you start your loop from j = len, the first character it prints is the null character, then it will print the printable characters in the remaining iterations. If you start your loop from len-1, it will print only the printable characters.
The extra spacing you're seeing is that null character. On some operating systems, printing a null character has no visible effect, but on your system it apparently prints a space.
This
for(int i=0; i<= len ; i++)
with len == 7 will loop for 0, 1, 2, 3, 4, 5, 6, 7;
because the execution will happen as long as the condition i<= len is true.
It will stop executing when it that condition is not true anymore, which does not apply before i==8.
For i==8 no execution will occur, but for 1 through 7 and for 0, i.e. 8 times.
The idiom to make a loop with len executions is
for(int i=0; i< len ; i++)
Codeforces problem 339A-http://codeforces.com/problemset/problem/339/A
I have tried to sort the values stored at even places of the array(starting from 0).I get an error while running the program or program returns a junk value.What is wrong with my solution?
My solution:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s[101],temp;
int i,j;
cin>>s;
for(i=0;i<strlen(s);i+=2) //Bubble sorting values at even values of i.'+' is stored at odd values of i.
{
for(j=0;j<(strlen(s)-i-2);j+=2)
{
if(s[j]>s[j+2])
{
temp=s[j];
s[j]=s[j+2];
s[j+2]=temp;
}
}
}
cout<<s;
}
Your compiler should have warned you about the problem (you did switch on all warnings, yes? always do that!): Once i==strlen(s)-1, the loop for j is essentially unbounded, by the magic of arithmetic rules for signed/unsigned values.
for(unsigned j=0; j+2+i < strlen(s); j+=2)
does not have this problem. (i should be unsigned as well.)
Or stop the loop for i earlier. The problem in your code is still there then, but you won’t run into it. But I believe that is the worse route to take – fix the bug, and then optimize by observing i doesn’t need to go as far up, because the last character already forms a sorted sequence.
For odd lengths len of s, the outer loop runs until i==len-1. The inner loop then terminates at len - len - 1 - 2. Since strlen returns an unsigned type, this evaluates to a very large unsigned number, causing the inner loop to read way beyond the end of s. Eventually you'll reach memory you don't have access to read or write, causing the crash.
You can fix this by ending the outer loop sooner
int len = strlen(s);
for(i=0;i<len-2;i+=2) {
for(j=0;j<(len-i-2);j+=2)
Change this:
for(i=0;i<strlen(s);i+=2)
Into this:
for(i=0;i<strlen(s) - 2;i+=2)
Otherwise the s value be handled beyond its end-point
here is my code
void bubble(int a[], int n){
for(int i=0; i<n; i++){
int swaps=0;
for(int j=0; j<n-i-1; j++){
if(a[j]>a[j+1]){
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
swaps++;
}
}
if(swaps==0)
break;
}
}