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++)
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.
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.
I'm struggling with solving this problem in C++.
I have a string: {A,A,B,C} and I want to print all possible permutations for this.
This would be 12:
AABC, AACB, ABAC, ABCA, etc...
I've written the following piece of code in which I have:
- a string which contains the letters A,A,B,C.
- a result string in which I will print each permutation when base condition of recursivity is fullfilled
- an array of integers which represent counters values for each digit: counters[3] = {2,1,1} which means there can be 2 A's, 1 B and 1C in a permutation.
- a function which should solve the problem in a recursive manner like this:
Start from initial string. From left to right of string check if counter for each character is greater than 0. If it is put the character in result[lvl] where lvl is the depth of the recursion. Then decrement the counter for that character's position. Do that for all the elements to the right of the current element and then backtrack all the way up and start with next element(second A).
The base case would be when all counters are equal to 0 print the solution then return.
Here is the code:
#include <iostream>
using namespace std;
char theString[4] = {'A','A','B','C'};
char resultString[4]={};
int counters[3] = {2,1,1};
void printPermutation()
{
for(int i=0; i<4; i++)
{
cout << resultString[i];
}
cout << endl;
}
void solvePermutations(int *counters, int lvl)
{
if(lvl == 4)
{
printPermutation();
return;
}
for(int i=0; i<4; i++)
{
if(counters[i] == 0)
{continue;}
else
{
resultString[lvl] = theString[i];
counters[i]--;
solvePermutations(counters, lvl+1);
counters[i]++;
}
}
}
int main()
{
int *ptr;
ptr = counters;
solvePermutations(ptr, 0);
return 0;
}
When I run the code I get this output instead of what I'm expecting(12 distinct permutations):
ACAB
ACBA
BAAA
BAAC
BACA
etc
More than 12 and with no logic(to me :D)
Please help me correct this and tell me what is wrong in my algorithm and help me understand it. Thank you.
You have one small logical error in your algorithm. You are using a counter[3] and a theString[4]. The idea here is that each index of counter should correspond to one letter, and hold the amount of that letter used.
With your loop you are using i<4. When i is 3 in that loop, you are trying to access counter[3] which is out of bounds. This in undefined behavior and you could be reading any int value.
To correct this, you simply need to decrease the loop to go to max 2 (i < 3) and change theString to an array of 3 elements, {'A', 'B', 'C'}.
char theString[3] = {'A','B','C'};
//...
for(int i=0; i<3; i++)
Hello I'm making a program to display the following if say './prog7x hello there ' was entered as command line argument:
argument 0 is "./prog7x", has length 8, contains 5 alphabetic characters
argument 1 is "hello", has length 5, contains 5 alphabetic characters
argument 2 is "there", has length 5, contains 5 alphabetic characters
Total length 18: ./prog7xhellothere
I'm having trouble with counting the alphabetic characters.
I have a function to get the length, but I don't understand how to display the character's counted after length is done.. here's the program so far...I've only been coding for a couple months so any advice is appreciated!
#include <cctype> //isalpha
#include <cstdio>
#include <cstring> //strlen
#include <cstdlib>
//Function to display what argument we're on
void displayArgument(char* arr1[],int num);
//Funtcion to get the length of a command line argument then,
//display number of alphabetical characters it contains
void displayLength(char* arr[],int length);
//Function to count the total length, concatenate together,
//and display results
//void displayTotalCat(char* arr2[],int total);
int main(int argc, char* argv[])
{
displayArgument(argv,argc);
displayLength(argv,argc);
return 0;
}
//Function to display what argument we're on
void displayArgument(char* arr1[],int num)
{
for(int i=0; i<num; i++) {
printf("Argument %d is ",i); //what argument we're on
printf("'%s'\n",arr1[i]);
}
}
//Funtcion to get the length of a command line argument then,
//display number of alphabetical characters it contains
void displayLength(char* arr[],int length)
{
for (int l=0; l<length; l++) { //what length that position is
int len=strlen(arr[l]); //what is the length of position l
printf("Length is %d,\n",len); //print length
for(int j=0; j< len ;j++) {
int atoi(strlen(arr[l][j]));
printf("Contains %d alphabetical characters",arr[l][j]);
}
}
}
//Function to count the total length, concatenate together,
//and display results
//void displayTotalCat(char* arr2[],int total)
Skip to the end if you just want the result, but let's walk through this together. Here is the problematic part of your code:
for(int j=0; j< len ;j++) {
int atoi(strlen(arr[l][j]));
printf("Contains %d alphabetical characters",arr[l][j]);
}
Currently, you are printing inside your loop. So let's pull that part out:
for(int j=0; j< len ;j++) {
int atoi(strlen(arr[l][j]));
}
printf("Contains %d alphabetical characters",arr[l][j]);
Great. Also, we can no longer print arr[l][j] outside of the loop (j is out of scope) so we will need some kind of variable declared beforehand. This also makes sense to help us count, since we will want to add to this variable when we determine a character is alphanumeric:
int alphas = 0;
for(int j = 0; j < len; j++) {
if(????){
alphas = alphas + 1;
}
}
printf("Contains %d alphabetical characters", alphas);
Notice that I also formatted your code a little. In general, programmers follow rules about spaces, indentation, naming etc. to make their code easier for others to read. So, how do we determine if a character is alphanumeric? We could use a series of if statements (e.g. if(arr[l][j] == '1') etc.) but that's not very smart. You were right to look into isalpha! First, add this to the top of your file:
#include <ctype.h>
Then, you should be able to call the isalpha function like this:
int alphas = 0;
for(int j = 0; j < len; j++) {
if(isalpha(arr[l][j])){
alphas = alphas + 1;
}
}
printf("Contains %d alphabetical characters", alphas);
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.