繁体   English   中英

如何制作一个函数在c中输入一个长度未知的字符串,类型为void

[英]How to make a function to input a string with unknown length in c with type void

我正在尝试创建一个输入未知长度字符串的函数,但我不希望它返回任何我希望它通过使用我传递的指针进行更改的内容。

这是我的尝试。

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

void get(char * string){

    int size=1;
    string = malloc(size);
    char c;
    int i=0;    

    while(1){
        c = getchar();
        if(c=='\n'){break;}
        string[i] = c;
        i++;
        string = realloc(string , ++size);
    }

    string[i] = '\0';

}

int main(){

    char *buff;

    printf("String :");
    get(buff);
    printf("%s" , buff);


    return 0;
}

我的 gcc windows os 上的输出:

PE

1- PE 是什么 2- 这里有什么问题 3- c=='\\n' 行是否适合测试,如果用户按下 Enter 或我应该使用 EOF 或其他什么

我对您的代码进行了一些更改,以便它使用传递给它的指针并处理输入中可能的EOF

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

void get(char **string){
    char *input = NULL;
    int result, index = 0;

    while (1) {
        result = getchar();
        if (EOF == result) { printf("\n"); break; }
        if ('\n' == result) break;
        char *temp = realloc(input , index + 2);
        if (NULL == temp) {
            perror("Could not increase memory for string");
            if (input) free(input);
            exit(1);
        }
        input = temp;
        input[index++] = (char) result;
    }

    if (input) {
        input[index] = '\0';
        *string = input;
    }
}

int main(void) {
    char *buff = NULL;
    printf("String : ");
    get(&buff);
    if (buff) {
        printf("%s\n" , buff);
        free(buff);
    }
    return 0;
}

输出

$ ./main
String : a short string
a short string
$ ./main
String : input with EOF
input with EOF

笔记

我尽我所能处理错误情况,但我不确定我是否抓住了一切。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM