Input string with getchar

只谈情不闲聊 提交于 2019-12-07 07:23:39

问题


I am trying to read a string into a char array with a length chosen by the user. The problem is that getchar() doesn't stop reading until the user manually enters a newline by pressing enter, based on my code. I have read through other's threads, and I understand why I'm not able to do it this way, it's just completely contradictory to my assignment handout.

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

int main(void) {
    int nchars = chPrompt(nchars);
    char str[nchars];

    strInput(str, nchars);

    return 0;
}

int chPrompt(int nchars) {
    printf("How many chars do you need to input? >");

    return scanf("%i", &nchars);
}

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

    while((str[i] = getchar()) != '\n') {
        if(i > nchars-1)
            break;
        i++;
    }
    str[i] = '\0';

    //Troubleshooting
    printf("%s %d", str, strlen(str));
}

This is what the handout says:

Input a string from the keyboard (spaces included) using the technique we talked about (while with getchar(), not gets() , fgets()or scanf() ), augmented so that it will input any amount up to, but no more than, 80 characters. Be sure that there’s a null in the proper location after the input.

The technique we talked about in class was the while loop with getchar assignment to char array.

My question: My professor is very adamant about his instructions. In this handout, he is specifically telling me to input any amount up to, but no more than, 80. This is contradicting the functionality of getchar, correct? Is there any way to limit the length of a string, using this 'technique'?

On some of the threads I found, people mentioned it might be OS dependent. So, if that matters, I am on Windows 8.1.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/26963664/input-string-with-getchar

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