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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With