从命令行界面获取输入strinng [英] Get input strinng from command line innterface

查看:98
本文介绍了从命令行界面获取输入strinng的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在尝试从键盘输入输入字符串,然后存储该数据,以便我可以在其他功能中使用它,我无法解决。请指出我做错了什么。

谢谢



我尝试了什么:



Hello everyone,
I am trying to get input string from the keyboard and then store that data so i can use it in other function which i am not able to.can you please point out that what am i doing wrong.
Thank you

What I have tried:

static char get_input(_CLI *const PtrCLI)
{
    char input[1024];
    
    /* get string */
    printf("Enter input data of size less than 1024 bytes and write end to end the data: ");
    fgets(input,1024,stdin);
    
    /* create buffer and copy */
    InData = (char *)malloc( strlen(input) + 1);
    strlcpy(InData, input, 1024);
    return InData;
    
}

推荐答案

InData

假设它是 char *



你的功能应该是什么喜欢(不是最好的解决方案,但代码变化最小):



What is the type of InData ?
Assuming it is char *

Your function should be something like (not the best solution but with minimum changes in your code):

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

static char* get_input()
{
   char input[1024];

   /* get string */
   printf("Enter input data of size less than 1024 bytes and write end to end the data: ");
   fgets(input, 1024, stdin);

   /* create buffer and copy */
   char * InData = (char *)malloc(strlen(input) + 1);
   strncpy_s(InData, 1024, input, 1024);
   return InData;
}


我会模仿 C 运行时 API (即内存处理是调用者的责任):

I would mimic the C runtime API (i.e. memory handling is caller responsibility):
char * get_input(char * buffer, size_t buffer_size)
{
   /* get string */
   printf("Enter input data of size less than %u bytes and write end to end the data: ", buffer_size);
   return fgets(buffer, buffer_size, stdin);
}


这篇关于从命令行界面获取输入strinng的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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