新手 c 語言 字句問題

本帖最後由 ben6000 於 2010-1-20 18:48 編輯

#include <stdio.h>

int main () {
  
  char name[10];
  int i ;

  printf("what is your name ?");
  for (i=0;i<10;i++)
   scanf("%c",&name);

  for (i=0;i<10;i++)
  printf("%c",name);

  getchar ();
  return 0;
}
假設我輸入ben 三字後按enter ,佢都唔會做下一行,一定要入齊10個字,
咁我想問有咩辦法?可以只入我個名,其他吉左佢

- for (i=0;i<10;i++)
-   scanf("%c",name[i]);
+ scanf("%s", name);

but beware of buffer overrun.

TOP

回復 2# davidtlwong


    做唔到,complier 出error

TOP

scanf("%9s",name);

TOP

for loop is usually for looping which knowing the number of loop ....

scanf("%c", &name);

TOP

回復 5# Jason


   & 係我打漏左

TOP

回復 4# travel


    都係唔得

TOP

本帖最後由 TKY 於 2010-1-21 01:03 編輯

Replace the for loop by scanf("%s",name);
  1. printf("what is your name ?");
  2. scanf("%s",name);
複製代碼
And for the display, you'd better modify it to sth like this:
  1. for (i=0;i<strlen(name);i++)
  2.     printf("%c[i]",name);
複製代碼
or even like this:
  1. printf("%s",name);
複製代碼

TOP

因為你係用梗%c
所以print字出黎的時候要用name[i]

TOP

你地個意思係咁?
#include <stdio.h>

int main()
{
    char name;
    int i;
    printf("what is your name ?");
    scanf("%s",name);
    for (i=0;i<strlen(name);i++)
    printf("%c[i]",name);
    printf("%s",name);
  gatchar ();
  return 0;
}

TOP