使用 getchar 输入字符串 [英] Input string with getchar

查看:301
本文介绍了使用 getchar 输入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个字符串读入一个由用户选择的长度的字符数组.问题是 getchar() 不会停止阅读,直到用户根据我的代码按 Enter 手动输入换行符.我已经阅读了其他人的帖子,我明白为什么我不能这样做,这与我的作业讲义完全矛盾.

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

这是讲义上的内容:

使用我们谈到的技术从键盘输入一个字符串(包括空格)关于(虽然使用 getchar(),而不是 gets() 、 fgets() 或 scanf() ),增加,以便它可以输入任何数量,但不超过 80人物.确保输入后的适当位置有一个空值.

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.

我们在课堂上讨论的技术是将 getchar 赋值给 char 数组的 while 循环.

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

我的问题:我的教授对他的指示非常坚持.在这个讲义中,他特别告诉我输入最多但不超过 80 的任何数量.这与 getchar 的功能相矛盾,对吗?有没有办法使用这种技术"来限制字符串的长度?

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'?

在我发现的一些线程中,人们提到它可能依赖于操作系统.所以,如果这很重要,我使用的是 Windows 8.1.

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

推荐答案

Op 的代码已关闭.

getchar() 不会停止阅读,直到用户通过按 Enter 手动输入换行符"是不正确的.
典型的用户输入是行缓冲.在 Enter 发生之前,什么都不会给程序.那时整行都给了程序.getchar() 一次从 stdin 消耗 1 个 char.

"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) 需要分配足够的缓冲内存@Grzegorz Szpetkowski
2) 将输入读取为 int 并根据需要读取额外内容.
3) 不要将 scanf() 的值作为要读取的数量返回.
4) 读完要读的char个数后,再读剩余的行.@Grzegorz Szpetkowski

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() 返回一个 unsigned charEOF.这通常是 257 个不同的结果.将 getchar() 读入 char 就失去了这种区别.

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

注意:strlen() 返回类型 size_t,而不是 int,这在您的平台上可能/可能不同,最好使用正确的格式说明符 "%zu"strlen().或者使用:

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

这篇关于使用 getchar 输入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆