4

我对编程完全陌生(大学第一学期),我跟不上我的讲师。目前我被困在这个练习上(比我愿意承认的时间要长得多)。我试图在互联网上(在这个网站和其他网站上)寻求帮助,但我不能,因为我们的讲师让我们使用一种非常简单的 c 形式。我不一定要求一个完整的答案。我真的很感激甚至一些关于我错在哪里的提示。我知道这对某些人来说可能真的很简单,这个问题可能看起来很无知或愚蠢,我为没有弄清问题而感到难过,但我需要尝试理解。

所以,我想做的是使用 scanf 和 do while 循环,这样用户就可以在数组中输入字符。但我不明白为什么当用户按下 ENTER 时循环不会停止。代码还有更多内容,但我正在尝试慢慢来,一步一步来。(我不允许使用指针和 getchar 等)。

#include <stdio.h>
main()
{
      char a[50];
      int i;

      printf("Give max 50 characters\n");

      i=0;

      do
      {
            scanf("%c", &a[i]);
            i=i+1;
      }
      while((i<=50) && (a[i-1]!='\0'));

            for(i=0; i<50; i++)
                 printf("%c", a[i]);
 }
4

3 回答 3

3

这里没有任何以 nul 结尾的字符串,而只有字符串数组。

因此,当按 enter 时,a[i-1]不是(使用as 参数\n不会以nul 终止字符串,并且 ENTER 只是一个代码为 10 AKA 的非 nul 字符)\0scanf%c\n

然后不要打印字符串的其余部分,因为你会得到垃圾,只需i在打印字符串时重用:

#include <stdio.h>
main()
{
      char a[50];
      int i;

      printf("Give max 50 characters\n");

      i=0;

      do
      {
            scanf("%c", &a[i]);
            i=i+1;
      }
      while((i<sizeof(a)) && (a[i-1]!='\n'));  // \n not \0
      int j;
      for(j=0; j<i; j++)  // stop at i
            printf("%c", a[j]);  // output is flushed when \n is printed
 }

i<50也用not进行测试,i<=50因为a[50]它超出了数组范围(我已经概括为sizeof(a)

于 2018-01-04T13:29:17.807 回答
2

这是您可以执行此操作的另一种方法。

#include <stdio.h>

// define Start
#define ARRAY_SIZE              50
// define End

// Function Prototypes Start
void array_reader(char array[]);
void array_printer(char array[]);
// Function Prototypes End


int main(void) {

    char user_input[ARRAY_SIZE];
    printf("Please enter some characters (50 max)!\n");
    array_reader(user_input);

    printf("Here is what you said:\n");
    array_printer(user_input);

    return 0;
}


// Scans in characters into an array. Stops scanning if
// 50 characters have been scanned in or if it reads a
// new line.
void array_reader(char array[]) {

    scanf("%c", &array[0]);

    int i = 0;
    while (
           (array[i] != '\n') &&
           (i < ARRAY_SIZE)
          ) {

        i++;
        scanf("%c", &array[i]);
    }

    array[i + 1] = '\0';
}


// Prints out an array of characters until it reaches
// the null terminator
void array_printer(char array[]) {

    int i = 0;
    while (array[i] != '\0') {
        printf("%c", array[i]);
        i++;
    }
}
于 2018-06-05T15:21:42.223 回答
1

您可以尝试使用以下代码:

#include <stdio.h>

main()
{
  char a[50];
  int i;

  printf("Give max 50 characters\n");

  i=0;
  do {
    scanf("%c", &a[i]);
    i=i+1;
  } while(i<50 && a[i-1] != '\n');
  a[i] = 0;

  for(i=0; a[i] != 0; i++)
    printf("%c", a[i]);
}

该函数scanf("%c", pointer)将一次读取一个字符并将其放置在该pointer位置。您正在寻找'\0',这是一个有效的字符串终止符,但是当您按 ENTER 时获得的换行符是您应该寻找的'\n'

'\0'此外,最好通过在末尾添加 a(实际上是零)来终止您已阅读的字符串。然后使用它来停止打印,或者您可以打印未初始化的 char 数组内容的“其余部分”。

于 2018-01-04T13:41:47.517 回答