a.exe has stopped working - c

#include<stdio.h>
#include<conio.h>
#include<string.h>
char *createP(int);
int main()
{
int n,i;
char str[100];
printf("int n = ");
scanf("%d",&n);
printf("string str = ");
scanf("%s",&str);
if(n>40)
return -1;
for(i=0;i<strlen(str);i++)
if(str[i]=='X' || str[i]=='Y' || str[i]=='Z')
continue;
else
return -1;
char *P;
P=createP(n);
printf("The generated string is = %s",P);
return 0;
}
char *createP(int n)
{
if(n==0)
return "X";
if(n==1)
return "Y";
if(n==2)
return "Z";
if(n>2)
return strcat(createP(n-2),createP(n-3));
}
I am trying to create a string for the following question :
P(0) = 'X'
P(1) = 'Y'
P(2) = 'Z'
P(n) = P(n-2) + P(n-3), n>2
where + denotes string concatenation.
I am using recursion (which looks quite obvious) for this problem.But my .exe is not working.

You are using strcat wrongly.
char * strcat ( char * destination, const char * source );
Appends a copy of the source string to the destination string. The terminating null character >in destination is overwritten by the first character of source, and a null-character is >included at the end of the new string formed by the concatenation of both in destination.
Try using something like this instead,
char *createP(int n)
{
if(n==0)
return "X";
if(n==1)
return "Y";
if(n==2)
return "Z";
if(n>2)
{
char *P = calloc (n, sizeof(char));
strcat(P, createP(n-2));
strcat(P, createP(n-3));
return P;
}
}

You need to create a dynamic list, using only char *P don't let you use it as string at all.
Try to declare char P[100] , and at the end of the recursion put \0 char.
EDIT:
something like that:
void createP(int n,int index)
{
if(n==0)
P[index] = "X";
return ;
if(n>2)
return strcat(createP(n-2,index + 2),createP(n-3,index + 3));
}
While P is global string, and index start with 0.

Memory was not allocated correctly, I had the same problem when I declared
type array[20];
and than called array[20]=...;
The solution was that it was needed to declare type array[21];)

Related

How can I shift right after a certain point in the string?

My code provides the following parameters requested by the teacher:
But the teacher also wants this: "insertChar function should not overwrite any characters. It should insert the new character and offset remaining characters by one index."
how can I set this up? I mean how can I shift a string right from a certain point?
#include<stdio.h>
#include<string.h>
void insertChar(char string[], char c, int index) {
int len = 0;
int i;
for (i = 0; i > index; i--) {
string[i] = len;
string[i] = string[i-1];
string[i-1] = len;
}
string[index] = c;
}
int main() {
char string[100];
printf("Please input a string \n");
scanf ("%[^\n]%*c", string);
printf("Please input the character to be added to string.\n");
char c;
scanf ("%c", &c);
printf("Please input the index which the function will insert the character. \n");
int index;
scanf("%d", &index);
insertChar(string, c, index);
printf("%s", &string);
return 0;
}
How can I shift right after a certain point in the string?
(OP's insertChar() is too broken for repair.)
Watch out for 2 pitfalls: inserting well past the end of the string and exceeding the size of the buffer:
#include <string.h>
void insertChar(size_t buffer_size, char string[], char c, size_t index) {
size_t size_used = strlen(string) + 1;
if (size_used >= buffer_size) {
fprintf(stderr, "Buffer too small for insertion or existing string.");
} else if (index >= size_used) {
fprintf(stderr, "Inserting well past the end of the string.");
} else {
// Move the right portion of the string by 1 with memmove
// v----------------v Address one past the insertion point
memmove(&string[index + 1], &string[index], size_used - index);
// ^------------^ Insertion location
string[index] = c; // Insert
}
}
Usage
char string[100];
...
insertChar(sizeof string, string, c, index);

Issue with Strings in C

Here is a program with Strings where I am trying
Pig Latin translation is simply taking the first letter of a “word” and appending that letter to the end of the word with “ay” added to the end as well
I have issue with m1=m2+3 ( resetting the Initial Marker ).
Input that I am giving : "Alex, how are you right"
The output I am expecting is : lexay, owhay reay ouyay ightray
But
I am getting this : lex,Aay way ay ayo gayi
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void initialize(char english[], char piglatin[]);
void readinput (char english[]);
int countwords(char english[]);
void convert ( int words, char english[], char piglatin[]);
void writeoutput( char piglatin[]);
int main()
{
char english[80], piglatin[80];
int words;
initialize(english, piglatin);
printf("enter the string\t");
fflush(stdin);
gets(english);
printf ("\nInput buffer contents: %s\n", english);
words = countwords(english);
convert(words,english,piglatin);
writeoutput(piglatin);
printf ("Have a nice day\n");
}
void initialize(char english[], char piglatin[])
{
int count;
for(count =0; count<80;++count)
{
english[count]=piglatin[count]=' ';
}
return;
}
/* Scan the english test and determine the number of words */
int countwords(char english[])
{
int count, words =1;
for ( count =0;count <79;++count)
{
if(english[count]==' ' && english[count+1]!=' ')
++words;
}
printf("%d\n",words);
return (words);
}
/* convert each words in to piglatin*/
void convert ( int words, char english[], char piglatin[])
{
int n, count;
int m1=0;
int m2;
/* convert each word */
for ( n=1;n<=words;++n)
{
/* locate the end of the current word*/
count = m1;
printf ("\ before conversion word contents: %d\n", count);
while ( english[count]!=' ')
{
m2=count++;
}
printf ("\ before conversion word contents: %d\n", m2);
/* transpose the first letter and add 'a', 'y'*/
for (count =m1;count<m2;++count)
{
piglatin[count+(n-1)]=english[count+1];
}
piglatin[m2+(n-1)] = english[m1];
piglatin[m2+1] = 'a';
piglatin[m2+2] = 'y';
m1=m2+3;
printf ("\ Converted word contents: %s\n", piglatin);
}
return;
}
void writeoutput( char piglatin[])
{
int count =0;
for (count =0; count <80; ++count)
{
putchar(piglatin[count]);
}
printf ("\n");
return;
}
I see various problems here:
Alex -> lex,Aay: You should check for punctuation marks when determining the end of the words, thus inserting the Aay part before the comma character
Alex -> lex,Aay: Every character from the start of a word should be converted to lowercase and the resulting first character should be converted to upper case respectively
Now the conversion function: I have changed it a bit to get you started; it should work now ( at least it does with your test string ) without taking 1 and 2 into account though
void convert(int words, char english[], char piglatin[])
{
int estart = 0;
int ppos = 0;
int m2;
for (int n = 0; n < words; n++)
{
//locate the start of the current word, to make
//sure something like this is converted:
//"Alex, how are you"
while (english[estart] == ' ')
{
//make sure we do not exceed the strings boundaries!
if (english[estart] == '\0')
{
return;
}
estart++;
}
//locate the end of the word
int eend = estart;
while (english[eend] != ' ')
{
//never forget to check for the end of the string
if (english[eend] == '\0')
{
break;
}
eend++;
}
/* transpose the first letter and add 'a', 'y'*/
for (int i = estart+1; i < eend; i++, ppos++)
{
piglatin[ppos] = english[i];
}
piglatin[ppos++] = english[estart];
piglatin[ppos++] = 'a';
piglatin[ppos++] = 'y';
//dont forget to add a whitespace or your string might behave
//very stangely!
piglatin[ppos++] = ' ';
estart = eend;
printf("\ Converted word contents: %s\n", piglatin);
}
}
I hope this gets you started in the right direction.
Please also check your array sizes for english and piglatin. The string for piglatin is alway longer than the english one but your array sizes are the same! Also i would advise you add some boundary checks to make sure you do not leave the array boundaries.

Concatenation of two strings with discarding overlap

I need to build a function in C, that receives two strings str1 and str2 and returns a string that is the concatenation str1 and str2, but I need to discard the last elements of str1 that are equal to the first elements of str2.
Example 1:
str1 = ccabcc
str2 = ccbabd
result : ccabccbabd
Example 2:
str1 = abbcbf
str2 = ab
Result : abbcbfab
Sometimes there is no overlapping.
This problem is trivial imho. Personally, I would go with something like this(it is pseudo code):
function(str1,str2)
int j = 0
int lstr1 = lenght of str 1
int lstr2 = lenght of str 2
while(true)
if(str1[lstr1 - j] == str2[j])
j++
else
break
return str1 + str2[j to end of string]
If I did not make logic mistake, you code should look like something that compare the end of str 1 to beginning of str 2 and increment. Also, my pseudo code don't take into account the string lenght and potential overflow error.
I hope this is what you need:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *concate(char *first, char *second){
size_t len1 = strlen(first);
size_t len2 = strlen(second);
char *res = (char *)malloc(len1 +len2 +1);
if(res==NULL){
exit(1);
}
if(first[len1-1] == second[0]){
first[len1-1] = 0;
second++;
}
strcpy(res,first);
strcat(res,second);
return res;
}
int main(void){
int i = 0,len = 0;
char arr[] = "ccabcc";
char arr2[] = "ccbabd";
char *res = concate(arr,arr2);
while(res[len] != '\0'){
len++;
}
for(i=0;i<len;i++){
printf("%c",res[i]);
}
printf("\n");
free(res);
return 0;
}
Output:
ccabccbabd
int main(){
char a[256], b[256];
printf("Enter 1st string\n");
gets(a);
printf("Enter the 2nd string\n");
gets(b);
strcat(a,b);
printf("String concatenation is %s\n",a);
}

Count number of consonants in a string

Another starter question.
int counterConstant;
int x;
for(x = 0; x<20; x++){
if("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSVWXYZ".IndexOf(tempString[x]) >= 0){
counterConsonant++;
}
}
But I get an error:
"error: member reference base type 'char [42]' is not a structure or union"
Is there another way I could do this?
(I'm doing this inside a for that checks each char on the string.)
There are no objects in C, so there are no "methods" and you can't call IndexOf on a string literal. A string is nothing more than an array of characters in C.
With that in mind, let's see how you can actually loop over the characters of a string:
for (const char *p = tempString; *p != '\0'; ++p) {
/* loop body */
char c = *p; // *p is the current letter
}
This will create a pointer to the first element of the string, and then loop over all of the following characters, if you'd really prefer to use indexes, you could do
for (size_t i = 0, len = strlen(tempString); i < len; ++i) {
char c = tempString[i];
}
As far as checking each letter for consonant-ness, that you can write a helper function for
int is_consonant(char c) {
c = tolower(c); // #include <ctype.h>
if (!isalpha(c)) return 0; // if not a letter, return false
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return 0;
default:
return 1;
}
}
now back to your loop, use this function to check each character.
int consonant_count = 0; // the =0 is important!
for (const char *p = tempString; *p != '\0'; ++p) {
if (is_consonant(*p)) {
++consonant_count;
}
}
If you don't initialize to 0, the initial value of consonant_count is unpredictable, so make sure you do.
If you are working on C (as it was specified in tags), strchr() method is used to search a char in a string, and strstr() is used to search a string in a string. We will use strchr() here because tempString[x] is a char. Also, don't forget to give your int variable an initial value. Try this code:
int main()
{
int counterConsonant = 0;
int x;
const char* tempString = "12345678901234567890";
for (x = 0; x<20; x++){
if (strchr("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSVWXYZ", tempString[x]) != NULL){
counterConsonant++;
}
}
return 0;
}
C is a structured procedural language, so it doesn't have member functions/methods like a "true" object-oriented programming language such as C#. You could use a combination of strspn and strcspn like below to count sequences of consonants and non-consonant characters respectively, based on a predefined list of consonant characters:
#include <string.h>
size_t
count_consonants (const char *s)
{
size_t n;
size_t total = 0;
const char *consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
/* While we haven't reached the end of the string,
execute the code in the body of the loop. */
while (*s != '\0')
{
/* Count the number of consonants starting at the current string position. */
n = strspn (s, consonants);
/* Add the number of consonants counted to
the total number of consonants found. */
total += n;
/* Advance the character pointer to the next character
that IS NOT a consonant, based on the number of consonants
stored in `n'. */
s += n;
/* Advance the character pointer to the next character
that IS a consonant (`strcspn' = skip the characters in
`s' that don't appear in `consonants'). */
s += strcspn (s, consonants);
}
return total;
}
char temp[20];
scanf("%s",temp);
int i,j, consonantsCounter=0;
char consonants[]={'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z','B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','V','W','X','Y','Z'}
for(i=0;i<20;i++){
for(j=0;j<(sizeof consonants) / (sizeof consonants[0]);j++){
if(temp[i]==consonants[j]){
consonantsCounter++;
}
}
}

To insert a substring in the given string:Error:15 [Warning] return makes integer from pointer without a cast

I wish to insert a substring in the main string from the given position c which is user entered but i am constantly getting this warning
Header File:
char insstr(char a[100],char b[100],int c){
int i,j,t;
while(b[i]!='\0'){
i++;
}
i=t;
i=0;
for(j=c;j<t;j++){
a[j]=b[i];
i++;
}
return a;
}
Main File:
#include<stdio.h>
#include"Q7.h"
main(){
char x[100],y[100],f;
printf("Enter the main string \n");
gets(x);
printf("Enter the substring \n");
gets(y);
printf("Enter the position from where you want to enter the string");
scanf("%d",f);
printf("%s",insstr(x,y,f));
}
Strings are usually represented as char arrays i.e. char[] or char*. Since you are returning a string from the function, the return type should be char*.
char* insstr(char a[100],char b[100],int c)
{
/* ... */
}
You don't initialize i in insstr() before using it. This:
int i,j,t;
while(b[i]!='\0')
{
i++;
}
Should be:
int i,j,t;
i = 0;
while(b[i] != '\0')
{
i++;
}
Or, instead of reinventing the wheel, you should be using strlen(b) instead.
This is just wrong:
i=t;
i=0;
You didn't initialize t, and you are assigning to i twice. You end up obliterating whatever was stored in i. And of course, you are overwriting the contents of a without taking care of what was there. You are not inserting a string into a, you are replacing part of it with b. And then of course, as mentioned in other comments and answers, the return value should be char *.
Why not something as simple as this:
char *insstr(char *a, char *b, int c)
{
size_t a_len = strlen(a);
size_t b_len = strlen(b);
strcat(a, b);
reverse(a+c, a_len-c);
reverse(a+a_len, strlen(b));
reverse(a+c, a_len-c+b_len);
return a;
}
Where reverse() is:
void reverse(char *str, size_t len)
{
size_t i = 0, j = len-1;
while (i < j)
{
char tmp = str[i];
str[i] = str[j];
str[j] = tmp;
i++;
j--;
}
}
The algorithm works by concatenating b to a and then doing the appropriate swaps to move b into the right spot. In general, you can think of a as a string that can be decomposed into two blocks, ac, where c is the block after the insertion point where b will stay. When you concatenate b to the original string, you get acb. Moving b to the spot before c is a matter of reversing c, reversing b, so that you get a c_r b_r, and then you reverse c_r b_r, getting bc - just what you wanted.
A small example of how to use it:
int main(void)
{
char str1[100] = "Hello!";
char str2[] = ", world";
insstr(str1, str2, 5);
printf("%s\n", str1);
return 0;
}
This prints:
Hello, world!
Remember that you must make sure that a is indeed large enough to hold b. In general, you should pass the size of a as an argument, so that you can take appropriate action if a is not big enough, or, alternatively, you can make your code ensure that insstr() is not called if a is not big enough.
And please don't use gets(). Always use fgets(). It doesn't hurt, it is not complex, and it shows that you care.
NOTE: this idea is generalized in the book Programming Pearls as an efficient and elegant way to implement string rotations (which is what you want after appending b). Off the top of my head, I think it is mentioned in the "Aha! Algorithms" column.
#include<stdio.h>
#include<stdlib.h>
int insstr ( char *str, char *ins, int at) {
int each;
int len = 0;
int lenstr = 0;
int lenins = 0;
while ( str[lenstr] != '\0') {
lenstr++;
}
while ( ins[lenins] != '\0') {
lenins++;
}
if ( at > lenstr) {
at = lenstr; // force at to length of str if needed
}
len = at;
for ( each = 0; each <= lenins; each++) {
str[len] = ins[each]; // append ins onto str
len++;
}
return 1; // return true
}
int main() {
char input[300];
char substr[300];
char position[300];
int insert;
int each;
printf ( "Enter a string.\n");
fgets ( input, sizeof ( input), stdin);
each = 0;
while ( input[each] != '\n') {
each++;
}
input[each] = '\0'; // remove new-line
printf ( "Enter sub-string.\n");
fgets ( substr, sizeof ( substr), stdin);
each = 0;
while ( substr[each] != '\n') {
each++;
}
substr[each] = '\0'; // remove new-line
printf ( "Enter position to insert sub-string.\n");
fgets ( position, sizeof ( position), stdin);
insert = atoi ( position); // make position an integer
if ( insstr ( input, substr, insert)) {
printf ( "%s\n", input); // insert is successful. print it.
}
return 0;
}

Resources