I wrote a function that remove a given char from a string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* input_long(void);
void removeChar(char str[], char ch);
void main()
{
char *str, ch;
str = input_long();
printf("\nplease enter a char to be removed from the string: ");
scanf("%c", &ch);
removeChar(str, ch);
printf("the string after the removal is %s \n", str);
free(str);
}
void removeChar(char str[], char ch) //this function removing a given char from a given string//
{
int i, j = 0;
for (i = 0; str[i] != '\0'; i++) //looping the string until its end//
{
if (str[i] != ch) //by that we ensure the char will be erased from the string //
{
str[j] = str[i];
j++;
}
}
str[j] = '\0'; //the end of the new string after the whole process//
}
char* input_long(void) //this function gets a string dynamically allocated//
{
char tempstr[80], *str;
printf("enter a string\n");
gets(tempstr);
str = (char*) malloc((strlen(tempstr) + 1) * sizeof(char));
strcpy(str, tempstr);
return str;
}
My code didnt run well; when I run it, it seemed to lead the statement which asks the user to enter a string. I repaired the code by adding _flushall() , and now the code is running well:
_flushall();
str=input_long();
printf("\nplease enter a char to be removed from the string: ");
scanf("%c", &ch);
I dont really understand why adding that statement indeed repaired it.
Related
I know I essentially need to replace the "\n" with a "\0", but how would I access the array to incorporate this? I can not use string.h library or any other libraries.
#include <stdio.h>
#include <stdlib.h>
int main() {
char buffer[32];
char digits[3];
printf("Enter name:");
fgets(buffer,32,stdin);
printf("Enter age:");
fgets(digits,3,stdin);
char *name;
name = buffer;
int *age;
age = atoi(digits);
happyBirthday(name,age);
return 0;
}
int i = 0;
while (buffer[i] != '\0')
{
if (buffer[i] == '\n') buffer[i] = '\0';
++i;
}
I have tried make a program which is fills up a string array with string that is given by the user and after that i run into a problem with the idea that how coud i examine that how many words are in the array. I examined the whitespace characterts but it does not work well, i guess .Because whatever the array contains ,it writes flase value : e.g its contain 2 words when there is only 1 word in it.
int db =0;
char array[255];
void string(char str[]){
printf("Enter a string:");
scanf("%s",str);
}
void words(char str[]){
int i=0;
int len = strlen(str);
while( str[i]!=len)
{
if(str[i]==' ')
db++;
i++;
}
}
int main(int argc,char** argv){
string(array);
words(array);
printf("its contain %d words",db);
}
You have a few problems, but the main is using scanf instead of gets. If you'll run this function you'll see that scanf fails to read beyond whitespace, where gets doesn't: (my input was "123 456 789")
void string(char str[]){
printf("Enter a string:");
scanf("%s",str);
printf("%s\n", str); // the string was scanned until 1st whitespace
gets(str);
printf("%s\n", str); // proper string was read
}
The 2nd thing to note is warnings. The return type of strlen() isn't int, it's size_t (man). Also, you are comparing not matching types (char != int):
void words(char str[]){
int i=0; // change to size_t because it is checked against len
int len = strlen(str); // change to size_t
while( str[i]!=len) // should be i != len because you check the location in the string against the length, not against the char itself!!
{
if(str[i]==' ')
db++;
i++;
}
}
The 3rd thing is logic. What if your string has indeed 2 words: "hello world"? you would only count white_spaces and assume you have only one word. I would add something like:
void words(char str[]){
size_t i=0;
size_t len = strlen(str);
printf("%s\n", str);
while(i!=len)
{
if(str[i]==' ')
db++;
i++;
}
if(i) // if i is positive, there must have been a white_space -> add the 1st word because it wasn't counted (Assuming the string must start with a word and not a white_space!!)
i++;
}
This is how I would rewrite it:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int db =0;
char array[255];
void string(char str[]){
printf("Enter a string:");
gets(str);
}
void words(char str[]){
size_t i = 0;
size_t len = strlen(str);
while(i != len)
{
if(str[i]==' ')
db++;
i++;
}
if(i)
i++;
}
int main(/*no need for argc, argv. You can leave them there, but I prefer to omit if not used*/){
string(array);
words(array);
printf("its contain %d words",db);
return 0;
}
Note that there are still some issues:
What happens if more than one white space is entered between 2 words?
What happens if a white space is the first char (I assumed not, but can it be?)
What happens if the input string is too long?
Analyse main() function
int main(int argc,char** argv){
string(array);
words(array);
printf("its contain %d words",db);
}
when you are calling words(array) function what is array ? nothing. if you are taking array as a global then what's the the needs of passing to function & catching with str .
Next,
void string(char str[]){
printf("Enter a string:");
scanf("%s",str);
}
modify above function as below if you want to scan strings with white spaces.
void string(char str[]){
int len;//define it
fgets(str,len,stdin);//TO READ STRINGS WITH WHITESPACES
}
Next come to your logic, what you want to achieve with while( str[i]!=len) ?
Rotate loop upto NULL & and then modify the condition for finding no of words as below.
void words(char str[]){
int i=0;
// int len = strlen(str);
while( str[i]! = NULL)
{
if(str[i]==' ' && str[i+1] !=' ')
db++;
i++;
}
}
complete program as
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void words(char str[]);
int db =0;
char array[255];
void string(char str[]){
int n;// define it
printf("Enter a string:");
fgets(str,n,stdin);// now data is there in str not in array variable thats why call words() function from here only it's a better option
words(str);// call from here bcz now you have str
}
void words(char str[]){
int i=0;
printf("string = %s \n",str);
while( str[i] != '\0')
{
if( (str[i]==' ' && str[i+1] !=' ') || str[i+1] == '\0')
db++;
i++;
}
printf("db = %d \n",db);
}
int main(int argc,char** argv){
string(array);
printf("its contain %d words",db);
}
I hope it will helps.
I thought it's the easiest one. You have to start with your counter
int db = 1;
I wrote a function that removes a given char from a string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* input_long(void);
void removeChar(char str[], char ch);
void main()
{
char *str, ch;
str=input_long();
printf("\nplease enter a char to be removed from the string: ");
scanf("%c", &ch);
removeChar(str, ch);
printf("the string after the removal is %s \n", str);
free(str);
}
void removeChar(char str[], char ch) //this function removing a given char from a given string//
{
int i,j = 0;
for (i = 0; str[i] != '\0'; i++) //looping the string until its end//
{
if (str[i] != ch) //by that we ensure the char will be erased from the string //
{
str[j] = str[i];
j++;
}
}
str[j]='\0'; //the end of the new string after the whole process//
}
char* input_long(void) //this function gets a string dynamically allocated//
{
char tempstr[80], *str;
printf("enter a string\n");
gets(tempstr);
str=(char*)malloc((strlen(tempstr)+1)*sizeof(char));
strcpy(str,tempstr);
return str;
}
My code didn't run well; when I ran it, it seemed to lead the statement which asks the user to enter a string. I repaired the code by adding _flushall() , and now the code is running well:
_flushall
str=input_long();
printf("\nplease enter a char to be removed from the string: ");
scanf("%c", &ch);
I don't really understand why adding that statement indeed repaired it.
I tried to compile and run the following program to reverse a string using the gcc compiler for linux but it shows the error : segmentation fault (core dumped).I even tried to debug using gdb but it didn't help. The program given below firstly inputs t which is the number of test cases.I tested the program with 3 test cases but after taking the 2nd input from user, the compiler shows error.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* strrev(char*);
int main(int argc, char *argv[])
{
int t,i=0,temp=0;
char *str[10],*rev[10];
scanf("%d",&t); //input the number of test cases
while(i<t)
{
scanf("%s",str[i]);
i++;
}
while(temp<t) //reverse the string and display it
{
rev[temp]=strrev(str[temp]);
printf("%s \n",rev[temp]);
temp++;
}
return 0;
getchar();
}
Function to reverse the string:
char *strrev(char *str)
{
int i = strlen(str)-1,j=0;
char ch;
while(i>j)
{
ch = str[i];
str[i]= str[j];
str[j] = ch;
i--;
j++;
}
return str;
}
You are getting segmentation fault because you haven't allocated space for elements of str.
You need to allocate memory first in main function.
scanf("%d",&t); //input the number of test cases
if(t <= 10)
for(size_t i = 0; i < t; i++)
str[i] = malloc(50); // Assuming string is no more than 50characters.
else
exit(0);
Beside this there are many flaws in your code. Here is the code after fixing them
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void strrev(char*); // Change return type to void
int main(void)
{
int t,i=0,temp=0, ch;
char *str[10];
scanf("%d",&t); //input the number of test cases
while((ch = getchar()) != EOF && ch != '\n'); // To consume newline character after scanf
// Allocate memory for str elements
if(t <= 10)
for(size_t i = 0; i < t; i++)
str[i] = malloc(50); // Assuming string is no more than 50characters.
else
exit(0);
i = 0;
while(i < t)
{
fgets(str[i],50,stdin); // Use fgets instead of scanf to read string
i++;
}
while(temp<t) //reverse the string and display it
{
// Since you are reversing string by flipping the characters the same
// string just pass pointer to it. str[temp] will be updated in function.
strrev(str[temp]);
printf("Reverse is %s \n", str[temp]);
temp++;
}
return 0;
}
void strrev(char *str)
{
size_t i = strlen(str)-1,j=0;
char ch;
while(i>j)
{
ch = str[i];
str[i]= str[j];
str[j] = ch;
i--;
j++;
}
//printf("Reverse is %s \n", str);
}
you have missed to allocate memory before reading char* value, so you can do this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* strrev(char*);
int main(int argc, char *argv[])
{
int t,i=0,temp=0;
char *str[10],*rev[10];
scanf("%d",&t); //input the number of test cases
while(i<t)
{
str[i] = (char*)malloc(100); // just allocate memory
scanf("%s", str[i]);
i++;
}
while(temp<t) //reverse the string and display it
{
rev[temp]=strrev(str[temp]);
printf("%s \n",rev[temp]);
temp++;
}
return 0;
getchar();
}
char *str[10],*rev[10];
You did not assign storage to hold string values yet for those pointers.
char * str; /* this is a string pointer */
char * str = malloc(15); /* this creates storage for a string */
char str[10]; /* this creates a static char array, also is a string */
I also had the same issue. I just fixed it by correcting the indices of the matrix.
#include <stdio.h>
main()
{
char* str;
char* strrev;
int i = 0;
int j = 0;
int c;
printf("Enter the string\n");
scanf("%[^\n]%*c", str);
while (*(str + i) != '\n')
{
i++;
}
for (c = i; c >= 0; c--)
{
*(strrev + j) = *(str + c);
j++;
}
}
This is my code to reverse a string. When I compile the code , it gives an error segmentation fault . Someone plz help me understand the error and realize my mistake.
Thanks
There are many issues:
You never allocate memory for str or strrev. This is why it crashes; writing to uninitialized pointers invokes undefined behavior, often resulting in a seg fault.
You're using scanf() with a complex conversion when you could just use fgets().
You should use strlen() rather than looping to find the end of the string.
char *str,*strrev;
first your char buffers where never initialized.
http://www.cplusplus.com/reference/cstring/strlen/
second use strlen to determine string len
regards
In addition to #unwind, even if you used str[100], the loop to find the length will fail. Since str doens not have a \n, the while() loop never ends.
// bad
char str[100];
scanf("%[^\n]%*c", str);
while (*(str + i) != '\n') {
i++;
}
// better
char str[100];
scanf("%99[^\n]%*c", str);
while (*(str + i) != '\0') { // look for \0
i++;
}
Following (some of) #unwinds pointers, here is some code that will reverse a string:
(you can use scanf(), but do not need such a complicated format string)
#include<stdio.h>
main()
{
char str[260],strrev[260];
int i=0, len;
printf("Enter the string\n");
scanf("%s",str);
len = strlen(str);
for(i=1;i<len;i++)
{
strrev[i-1] = str[len-i];
}
strrev[len]=0;
;
}
If you would like to avoid using scanf, then replace it with something like:
char str[260], strrev[260];
//...
fgets(buf, sizeof(str), stdin);
[EDIT-per comment] If still want to use a char *, do something like this:
#include<stdio.h>
main()
{
char *str, *strrev;
int i=0, len;
printf("Enter the string\n");
str = malloc(260);
strrev = malloc(260);
scanf("%s",str);
len = strlen(str);
for(i=1;i<len;i++)
{
strrev[i-1] = str[len-i];
}
strrev[len]=0;
free(str);
free(strrev);
}
Note: Other than keystroke counting, I am not sure how you would determine at run-time just how many characters will be entered by a user. So in this example, 260 bytes is assumed.
#include<stdio.h>
void main()
{
void mystrrev(char *);
char str[100];
char *p1;
p1=str;
printf("Enter the string..?\n");
scanf("%s",str);
mystrrev(p1);
printf("Reverse is =%s",p1);
}
void mystrrev(char *p1)
{
char rev[100];
char *r;
r=rev;
int i=-1,j=0;
while(*p1!='\0')
{
p1++;
i++;
}
while(i>=0)
{
p1--;
*r=*p1;
r++;
j++;
i--;
}
*p1='\0';
*r='\0';
while(j-1>=0)
{
r--;
j--;
}
while(*r!='\0')
{
*p1=*r;
p1++;
r++;
}
*p1='\0';
}
simple code