首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C控制台输入

C控制台输入
EN

Stack Overflow用户
提问于 2016-01-25 22:22:12
回答 5查看 642关注 0票数 1

我似乎无法搜索这一点,因为所有东西都是C++或C# (附带说明:搜索特定于C的任何简单方法吗?)我想弄清楚的是如何接受控制台字符串输入,使我知道它的长度,这样我就可以通过使用for循环向后索引返回它。我以前有过一些C++经验,但从未真正使用过控制台IO。任何帮助都很感谢,谢谢。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-01-25 22:34:35

  1. fgets()阅读。
  2. 处理可能出现的跟踪\n
  3. 查找长度
  4. 反向打印。 char buf100;if (fget( buf,sizeof buf,stdin) == NULL) Handle_EOF();bufstrcspn(buf,“n”)= '\0';// lop潜在拖尾\n size_t len = strlen(buf);而(len) {putc(buf-len,stdout);}
票数 2
EN

Stack Overflow用户

发布于 2016-01-25 22:35:30

您可以使用fgets函数从标准输入中读取。

代码语言:javascript
复制
char buf[80];

if (fgets(buf, 80, stdin) != NULL)
    /* buf now contains the first 80 chars of the input */

注意:不要使用,而不是,因为它很危险--它会使输入缓冲区溢出。

票数 1
EN

Stack Overflow用户

发布于 2016-01-25 23:15:18

您需要留出一些空间来存储输入;由于您事先不知道输入的大小,所以您将不得不在存储中获得一些创造性。

一种常见的策略是使用一个小的、固定大小的缓冲区从输入流中读取,并使用一个动态的、可调整大小的缓冲区来存储整个字符串,如果它的长度超过了固定大小的缓冲区所能处理的长度。通过这种方式,您可以以离散块读取任意长的输入行,然后将这些块粘贴到一起,根据需要调整目标缓冲区的大小。

您将从循环中的控制台读取固定大小的块,并将其存储到动态缓冲区,直到您看到换行符,此时退出输入循环。理想情况下,固定大小的缓冲区应该足够大以处理大多数合理的情况,这样就不需要扩展动态缓冲区。

过分冗长(未经检验!)示例:

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define INPUT_BUF_SIZE 21 // handle strings up to 20 characters in length

int main( void )
{
  /**
   * Set aside a fixed-size buffer to store input from the console.  This
   * buffer cannot be resized after it has been allocated.
   */
  char inputBuf[INPUT_BUF_SIZE]; 

  /**
   * Dynamically allocate a buffer to store the final string; 
   * its initial size is the same as the fixed buffer.  If necessary,
   * this buffer may be extended with the realloc function.  We're using
   * calloc instead of malloc to make sure the initial array contents
   * are set to 0.
   */
  char *finalBuf = calloc( INPUT_BUF_SIZE, sizeof *finalBuf ); 

  /**
   * finalBufSize tracks the total size of the dynamic buffer; finalBufLen
   * tracks the length of the string currently stored in the buffer.
   * These are not the same thing.  
   */
  size_t finalBufSize = INPUT_BUF_SIZE;
  size_t finalBufLen = 0; // initially no string stored in the buffer

  /**
   * Read from standard input into the fixed-size buffer; loop until
   * we see EOF or there's an error on input.
   */
  while ( fgets( inputBuf, sizeof inputBuf, stdin ) )
  {
    /**
     * If there isn't enough space left in finalBuf to store
     * the latest chunk, double the size of finalBuf.  This strategy
     * minimizes the number of times you have to call realloc (which
     * can be expensive).  
     */
    if ( strlen( inputBuf ) + finalBufLen > finalBufSize )
    {
      /**
       * *Always* assign the result of realloc to a temp variable; if the
       * call fails it will return NULL, and if you overwrite the value
       * of finalBuf with NULL, you'll lose your only reference to any
       * previously allocated memory.  
       */
      char *tmp = realloc( finalBuf, finalBufSize * 2 );
      if ( tmp )
      {
        finalBuf = tmp;
        finalBufSize *= 2;
      }
      else
      {
        /**
         * We can't extend the buffer anymore, so we'll exit the
         * loop and work with what we have.
         */
        fprintf( stderr, "Could not extend storage buffer, exiting input loop\n" );
        break;
      }
    }

    /** 
     * Append the input string to the target buffer.
     */
    strcat( finalBuf, inputBuf );
    finalBufLen = strlen( finalBuf );

    /**
     * Did we see a newline in the last input chunk?  If so,
     * remove that newline from the final string (unless you
     * want to include that in your reversal) and exit
     * the loop.
     */
    char *newline = strchr( finalString, '\n' );
    if ( newline )
    {
      *newline = 0; // overwrite the newline character with the string terminator
      break;
    }
  }

此时,finalBuf包含来自控制台的输入,您可以反转此字符串以进行输出。完成之后,释放使用free函数分配的内存,如下所示:

代码语言:javascript
复制
free( finalBuf );

理想情况下,您应该将所有这些输入处理分离到它自己的函数中,但就目前而言,这是一个足够好的说明。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35003554

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档