Input string with getchar

末鹿安然 提交于 2019-12-05 13:23:22

Op's code is close.

"getchar() doesn't stop reading until the user manually enters a newline by pressing enter" is incorrect.
Typical user input is line buffered. Nothing is given to the program until Enter occurs. At that time the entire line is given to the program. getchar() consumes 1 char at a time from stdin.

1) Need to allocate sufficient buffer memory @Grzegorz Szpetkowski
2) Read input as an int and read extra as needed.
3) Do not return the value from scanf() as the number of to read.
4) Read remaining line after reading the number of char to be read. @Grzegorz Szpetkowski

getchar() returns an unsigned char or EOF. That is typically 257 different results. Reading getchar() into a char loses that distinction.

void strInput(char str[], int nchars) {
  int i = 0;
  int ch;
  while((ch = getchar()) != '\n' && ch != EOF ) {
    if (i < nchars) {
       str[i++] = ch;
    }
  }
  str[i] = '\0';
}

int main(void) {
  int nchars = chPrompt(nchars);
  char str[nchars + 1];  // + 1
  strInput(str, nchars);

  //Troubleshooting
  printf("'%s' %zu", str, strlen(str));

  return 0;
}

int chPrompt(int nchars) {
  printf("How many chars do you need to input? >");
  if (scanf("%i", &nchars) != 1) {
    printf("Unable to read #\n"); 
    exit(-1);
  }

  // Consume remaining text in the line
  int ch;
  while((ch = getchar()) != '\n' && ch != EOF );

  return nchars;
}

Note: strlen() returns type size_t, not int, this may/may not be the same on your platform, best to use the right format specifier "%zu" with strlen(). Alternatively use:

printf("'%s' %d", str, (int) strlen(str));

This code could be corrected in few more places (e.g. counting the characters inputted so that you allow the user to input no more than 80 characters, etc.) but this will point you in the right direction:

#include <stdio.h>
#include <string.h>

void strInput(char str[], int nchars);

int main(void) {
    int nchars = 0;

    printf("How many chars do you need to input?\n");
    scanf("%d\n", &nchars);

    char str[nchars+1];

    strInput(str, nchars);

    return 0;
}

void chPrompt(int nchars) {
}

void strInput(char str[], int nchars) {
    int i = 0;

        char c;
    while((c = getchar()) != '\n' && i <= (nchars-1)) {
            str[i] = c;
            i++;
    }
    str[i] = '\0';

    printf("%s %d\n", str, (int)strlen(str));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!