Print a string using putch with pointers in C - c

So I'm trying to print an inputted string using putch and a little bit of pointers.
Here is my current code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void printer(char *c);
char *c;
char ch;
main(){
clrscr();
printf("Enter a string: ");
scanf("%s",&ch);
c = &ch;
printer(c);
getch();
}
void printer(char *c){
int x;
for(x=0;x<strlen(c);x++){
putch(*c);
}
}
The problem is that i can only print the first character of the string, also for some reason strlen always return 3 for strings that are 3 characters and below.
Do I have to use array for this so that I can use putch since it is limited to only 1 character output.

One of the problems is that your printer() function is not printing anything other than the first character. There are two ways of approaching this. Using pointers:
void printer(char const *c){
while ( *c != '\0' ) {
putch(*c);
c++;
}
}
And using pointer arithmetic:
void printer(char const *c) {
int x;
for ( x=0; x < strlen(c); x++ ) {
putch( *(c + x) );
}
}
The biggest problem is that you are attempting to store a string in a single character in memory. That's just asking for problems.
char ch;
scanf("%s",&ch); // NO NO NO NO NO
Instead declare your buffer (to store the string in) as an array big enough for the biggest string you expect:
char ch[512];
scanf("%s", ch);

First off, you pass a pointer to "storage for one character" to scanf. Anything that happens after that is in nsal demons territory.
Second, scanf does not allocate storage for your input, so even if you'd passed c instead of &ch, you would not be any better off.
Third, you really should be declaring your variables inside main rather than using global variables.
Something like this may be closer to what you actually want:
void output (char *c)
{
char *cp;
for (cp = c; *cp; cp++) {
putch(*cp);
}
}
int main (void)
{
char input[80];
printf("Please input a string: ");
scanf("%s\n", input);
output(input);
}

try this code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void printer(char *c);
char *c;
char buffer[1000];// use as a buffer
void main(){
clrscr();
printf("Enter a string: ");
scanf("%s",buffer);//read the input to the buffer
c=(char*)malloc(strlen(buffer)+1);//alloc memory with len of input + 1 byte to "\0"(end of string)
strcpy(c,buffer);//copy the input from the buffer to the new memory
printer(c);
getch();
free(c);//free the memeory
}
void printer(char *c)
{
int x;
for(x=0;x<strlen(c);x++){//move the index string pointer to next char in the string
putch(c[x]);//print the char to the screen
}
}
1)You cant use char to save a string u need char*!!!
2)You can get input to memory that not allocated!!!! because of that u must read the input to buffer after that alloc string by size of the input inside the buffer!

Your code print only first character because c is always pointing to first character of the array. For printing total string you need to increment character pointer as well
You need to do like this
void printer(char *c){
while(*c != '\0'){
putch(*c);
c++;
}
}

First calculate the length of the string & then use above implementation like this-
void printer(char *c){
int i, length;
length=strlen(c)
for(i=0;i<lenth;i++,c++){
putch(*c);
}
}
It should work I think.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void printer(char *c);
char *c;
char ch;//the ch should be a array
main(){
clrscr();
printf("Enter a string: ");
scanf("%s",&ch);//the ch don't need '&'
c = &ch;//the ch don't need '&'
printer(c);
getch();
}
void printer(char *c){
int x;
for(x=0;x<strlen(c);x++){
putch(*c);
}
}

Related

Segmentation fault (core dumped) in C in Linux

I'm trying to run this program by taking input from the user and I'm getting a Segmentation fault (core dumped) error. Can anyone help me to find out why this error is occurring and how can I fix this error? My code is given below:
// C program to remove the occurrences of a specific char from the given string.
#include <stdio.h>
char *squeeze(char *a[], int b){
int i,j;
for(i=j=0; *(*a+i)='\0';i++){
if(*(*a+i)!=b)
*(*a+j++)=*(*a+i);
}
*(*a+j)='\0';
return *a;
}
void main(){
char *c[1];
char d[2];
int e;
printf("Enter the string: ");
scanf("%s",*c);
printf("Enter the character to delete: ");
scanf("%c",d);
e=d[0];
printf("Resulting string is:%s.\n",squeeze(c,e));
}
You have a few problems in your code. First, as pointed out in the comments, your declaration of c as an array of char * length one is wrong. Declare it as an array of char or some max length. The will make the squeeze code simpler, with less dereferences. Next your for loop inside of squeeze is wrong, you have an assignment statement there in the middle, when you really want to check for inequality. Your second scanf needs a space in it to get rid of the white space character leftover in the input buffer. So, making these changes, your code should look something like this:
#include <stdio.h>
char *squeeze(char *a, int b){
int i,j;
for(i=j=0; *(a+i) != '\0';i++){
if(*(a+i)!=b)
*(a+j++)=*(a+i);
}
*(a+j)='\0';
return a;
}
int main() {
char c[100] = {0};
char d[2];
int e;
printf("Enter the string: ");
scanf("%99s",c);
printf("Enter the character to delete: ");
scanf(" %c",d);
e=d[0];
printf("Resulting string is: %s.\n",squeeze(c,e));
}
EDIT: Specify string length with scanf when reading in c.
// C program to remove the occurrences of a specific char from the given string.
#include<stdio.h>
char * squeeze(char a[], char b){
for(i=0; a[i]!='\0';i++){
if(a[i]==b){
a[i]=a[i+1];
while(a[i++]!='\0'){
a[i]=a[i+1];
}
}
}
return a;
}
int main(){
char c[50];
char d;
printf("Enter the string:");
scanf("%s",c);
printf("Enter the character to delete:");//add \n
scanf(" %c",&d);
printf("Resulting string is:%s\n",squeeze(c,d));
return 0;
}

Removing a character from string in C with a dynamic string

So, I want to create a function which creates and returns a dynamic string based on a string s without characters c. Now, I want to be able to remove all of the desired characters, no matter the case. Additionally, the original string entered by the user should remain unchanged. Here's my attempt, it keeps telling me about an error at line 12 (noted in the comments).
One more thing: I'm not sure if I wrote the remove function well, I think it should work? All of the pointers confused me a little bit.
#include <stdio.h>
#include <stdlib.h>
char * remove(char *s, char c);
int strlen(char *s);
int main() {
char s[16], c, n[16];
printf("Please enter string: ");
scanf("%s", s);
printf("Which character do you want to remove? ");
scanf("%c", &c);
n = remove(s, c); // Place the new string in n so I wouldn't change s (the error)
printf("The new string is %s", n);
return 0;
}
int strlen(char *s)
{
int d;
for (d = 0; s[d]; d++);
return d;
}
char * remove(char *s, char c) {
char str[16], c1;
int i;
int d = strlen(s);
str = (char)calloc(d*sizeof(char)+1);
// copying s into str so I wouldn't change s, the function returns str
for (i = 0; i < d; i++) {
while(*s++ = str++);
}
// if a char in the user's string is different than c, place it into str
for (i = 0; i < d; i++) {
if (*(s+i) != c) {
c1 = *(s+i);
str[i] = c1;
}
}
return str; // the function returns a new string str without the char c
}
You declared n as 16-element array of char type:
char n[16];
So you cannot do:
n = remove(s, c);
because n is a const pointer.
Also your remove function returns a pointer to its local array, which gets destroyed as soon as your function returns. Better declare remove as
void remove(char *to, char *from, char var);
and pass n as the first parameter.
There ware so many mistakes in your program it was easier to rewrite and show you, with added comments. Note that scanf("%s... will accept only a single word, not a sentence (it stops at the first whitespace). And note that the newline will be left in the input buffer for scanf("%c... to read unless you add a space, as advised.
#include <stdio.h>
void c_remove(char *n, char *s, char c) { // renamed because remove() is predefined
while (*s) { // no need for strlen()
if (*s != c) // test if char is to be removed
*n++ = *s; // copy if not
s++; // advance source pointer
}
*n = '\0'; // terminate new string
}
int main(void) { // correct signature
char s[16], c, n[16];
printf("Please enter string: ");
scanf("%s", s);
printf("Which character do you want to remove? ");
scanf(" %c", &c); // the space before %c cleans off whitespace
c_remove(n, s, c); // pass target string pointer too
printf("The new string is %s", n);
return 0;
}
Program sessions:
Please enter string: onetwothree
Which character do you want to remove? e
The new string is ontwothr
Please enter string: onetwothree
Which character do you want to remove? o
The new string is netwthree

how to reverse the integers between two strings with changing lower to upper & upper to case alphabets in c

I have an input string such as :"Hello 12345 WoRlD"
and I want output it as : "hELLO 54321 wOrLd"
1)here the lower case should be converted to upper and vice versa
2)reverse the integers between two strings
after executing it will only prints first string only and the rest of output vanishes
Here is what I have attempted so far
#include<stdio.h>
#include<string.h>
char* casechange(char *);
main()
{
char s[30],*p,*q;
int i,j;
printf("Enter string data:");
scanf("%s",s);
q=casechange(s);
printf("Manipulated string data:%s\n",s);
}
char* casechange(char *s)
{
int i,j=strlen(s)-1,num;
for(i=0;s[i];i++)
{
if(s[i]>='a'&&s[i]<='z')
{
s[i]-=32;
}
else if(s[i]>='A'&&s[i]<='Z')
{
s[i]+=32;
}
}
if(s[i]>='0'&&s[i]<='9'&&s[j]>='0'&&s[j]<='9')
//for(i=0;i<j;i++,j--)
//{
{
num=s[i];
s[i]=s[j];
s[j]=num;
}
//}
return s;
}
How can this be accomplished?
The problem with "after executing it will only prints first string only and the rest of output vanishes" is:
scanf("%s",s);
The scanf() '%s' format string tells scanf to read in a string, but only up to the first space. Hence, if you enter:
"Hello 12345 WoRlD"
The scanf("%s", s) will copy only "Hello" into 's'.
To fix this, change:
scanf("%s",s);
To this:
fgets(s, sizeof(s), stdin);
However, fgets() may leave a unwanted '\n' at the end of the string. The unwanted '\n' can be eliminated by inserting the following code after the fgets():
q=strchr(s,'\n');
if(q)
*q = '\0';
Then the output will be:
"hELLO 12345 wOrLd"
SPOILER ALERT!
See my version 'casechange()', which will also reverse the number.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char* casechange(char *);
int main(){
char s[30];
printf("Enter string data:");
scanf("%29[^\n]",s);//%s : separated by white space
casechange(s);
printf("Manipulated string data:%s\n", s);
return 0;
}
char* casechange(char *s){
int i;
for(i=0;s[i];i++){
if(islower(s[i]))
s[i] = toupper(s[i]);
else if(isupper(s[i]))
s[i] = tolower(s[i]);
else if(isdigit(s[i])){
int j, n;
char num[30];
sscanf(&s[i], "%29[0123456789]%n", num, &n);
for(j=0;j<n;++j)
s[i+j] = num[n-j-1];
i+=n-1;
}
}
return s;
}
else if(isdigit(s[i])){
int j, n;
char num;
sscanf(&s[i], "%*[0123456789]%n", &n);
for(j=0;j<n/2;++j){
num = s[i+j];
s[i+j] = s[i+n-j-1];
s[i+n-j-1] = num;
}
i+=n-1;
}

segmentation-error in ubuntu gcc

#include<stdio.h>
int main()
{
char *ch;
int n=10;
gets(ch);
puts(ch);
printf("%d\n",n);
}
#include<stdio.h>
int main()
{
char *ch;
int n=10;
gets(ch);
printf("%d\n",n);
puts(ch);
}
In the first one , the segmentation error occurs at print(n) and in second one it occurs at puts(ch).No error occurs if print(n) is also used just after declaring n.
gets() is dereferencing an unitialized pointer, causing undefined behaviour.
Allocate memory for ch and don't use gets() as there is no way to limit the number of characters read, meaning potentially writing beyond the bounds of the destination array.
Example using fgets():
char ch[128];
if (fgets(ch, 128, stdin))
{
}
Use fgets and allocate memory for your "buffer" (via malloc) to hold the given string. At the end call free for your pointer.
#include<stdio.h>
#include<stdlib.h>
int main(){
char * ch = (char*) malloc(sizeof(char)*10);
//or by using this: char ch[10];
int n=10;
gets(ch);
puts(ch);
printf("%d\n", n);
free(ch);
}

Using recursion to find the length of a string in C [duplicate]

Here is my code:
#include<stdio.h>
#include<string.h>
int string_length(char s[]);
main()
{
char s[50];
int l;
printf("Enter the string\n");
scanf("%s\n",s);
l=strlen(s);
printf("Length of string = %d\n",l);
}
int string_length(char s[])
{
int i;
i=0;
while(s[i] != '\0')
++i;
return i;
}
After compile it scan for two input values.
What's wrong with my code?
Get rid of the newline in the scanf.
scanf("%s",s);
That should get this code to work.
But I am unable to understand why you wrote a function to compute string length if you had to use strlen().
HTH,
Sriram.
You're calling strlen instead of your own string_length in main.
const size_t sillyStrlen(const char* text) {
if (*text) {
return sillyStrlen(text + 1) + 1;
}
return 0;
}
Buy a book, see The Definitive C Book Guide and List
Read about the language syntax
Learn how to use pointers
You've just learned how to write a int strlen(char[]) function.
Try This one.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char *str;
printf("Enter a string\n");
gets(str);
printf("The size of the string is %d",strlen(str));
getch();
return 0;
}

Resources