5

だから私は putch と少しのポインタを使って入力された文字列を印刷しようとしています。

これが私の現在のコードです:

#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);
  }
}

問題は、文字列の最初の文字しか出力できないことです。また、何らかの理由で strlen は、3 文字以下の文字列に対して常に 3 を返します。

1文字の出力に制限されているため、putchを使用できるように、これに配列を使用する必要がありますか?

4

6 に答える 6

1

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!

于 2013-07-11T11:31:03.020 に答える
1

まず、「1 文字分のストレージ」へのポインタを に渡しますscanf。その後のことは何でもナサル魔族のテリトリー。

次に、scanfは入力用のストレージを割り当てません。そのため、cの代わりに渡されたとしても&ch、状況は改善されません。

main第三に、グローバル変数を使用するのではなく、内部で変数を宣言する必要があります。

このようなものは、実際に必要なものに近いかもしれません:

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);
}
于 2013-07-11T11:35:21.423 に答える
0

最初に文字列の長さを計算し、次に上記の実装を次のように使用します-

void printer(char *c){
  int i, length;
  length=strlen(c)
 for(i=0;i<lenth;i++,c++){
    putch(*c);
  }
}

それはうまくいくはずです。

于 2013-07-11T11:43:07.787 に答える