如何在C中使用用户输入来使字符串函数? [英] How to make string function with user input in C?

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

问题描述

我知道如何在内部使用用户输入(当前正在使用scanf)使用int,double,float来实现功能.

I know how to make function with int, double, float with user input inside(im currently using scanf).

int getData(){
    int a;
    scanf("%i",&a);
    return a;
}

但是如何在内部使用字符串类型和用户输入来创建函数,然后我们使用string类型返回该值?

but how to make function with string type and user input inside, then we return that value with type string?

推荐答案

C字符串是char的数组,该数组以NUL(零)字节终止.数组通常作为第一个元素的指针传递.从函数返回该值的问题在于,指向的地址必须在该函数的生存期内保持有效,这意味着它必须是static缓冲区(然后,该缓冲区将被对该函数的任何后续调用所覆盖,打破早期返回的值)或由函数分配,在这种情况下,调用方负责释放它.

A C string is an array of char terminated by a NUL (zero) byte. Arrays are normally passed around as pointers to the first element. The problem with returning that from the function is that the address pointed to must remain valid beyond the lifetime of the function, which means it needs to be either a static buffer (which is then overwritten by any subsequent calls to the same function, breaking earlier returned values) or allocated by the function, in which case the caller is responsible for freeing it.

您提到的scanf对于读取交互式用户输入也是有问题的,例如,它可能会使输入处于意外状态,例如当您不使用换行符时, next scanf的调用(可能是在不相关的函数中)在遇到换行符时可能无法给出预期的结果.

The scanf you mention is also problematic for reading interactive user input, e.g., it may leave the input in an unexpected state such as when you don't consume the newline at the end of a line the next call to scanf (maybe in an unrelated function) may surprisingly fail to give the expected result when it encounters the newline.

通常更容易地将输入逐行读取到缓冲区中,例如使用fgets,然后从那里解析行. (某些输入您可能能够简单地通过逐个字符地读取而无需缓冲区来解析,但是这样的代码通常变得冗长且难以快速理解.)

It is often simpler to read input into a buffer line-by-line, e.g., with fgets, and then parse the line from there. (Some inputs you may be able to parse without a buffer simply by reading character by character, but such code often gets long and hard to follow quickly.)

读取任何可能包含除换行符以外的空格的字符串的示例如下:

An example of reading any string, which may contain whitespace other than the newline, would be something like:

/// Read a line from stdin and return a `malloc`ed copy of it without
/// the trailing newline. The caller is responsible for `free`ing it.
char *readNewString(void) {
    char buffer[1024];
    if (!fgets(buffer, sizeof buffer, stdin)) {
        return NULL; // read failed, e.g., EOF
    }
    int len = strlen(buffer);
    if (len > 0 && buffer[len - 1] == '\n') {
        buffer[--len] = '\0'; // remove the newline
        // You may also wish to remove trailing and/or leading whitespace
    } else {
        // Invalid input
        //
        // Depending on the context you may wish to e.g.,
        // consume input until newline/EOF or abort.
    }
    char *str = malloc(len + 1);
    if (!str) {
        return NULL; // out of memory (unlikely)
    }
    return strcpy(str, buffer); // or use `memcpy` but then be careful with length
}

另一个选择是让调用方提供缓冲区及其大小,然后在成功时返回相同的缓冲区,而在失败时返回NULL.这种方法具有 这样做的好处是,调用方可以决定何时重新使用缓冲区以及是否需要复制字符串或只是读取一次并忘记了该字符串.

Another option is to have the caller supply the buffer and its size, then just return the same buffer on success and NULL on failure. This approach has the advantage that the caller may decide when a buffer is reused and whether the string needs to be copied or simply read once and forgotten.

这篇关于如何在C中使用用户输入来使字符串函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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