[英]How to make string function with user input in C?
我知道如何使用int,double,float和內部用戶輸入來實現函數(我目前正在使用scanf)。
int getData(){
int a;
scanf("%i",&a);
return a;
}
但是如何使用字符串類型和內部用戶輸入來創建函數,然后我們使用字符串類型返回該值?
AC字符串是由NUL(零)字節終止的char
數組。 數組通常作為第一個元素的指針傳遞。 從函數返回該值的問題在於,指向的地址必須在該函數的生存期內保持有效,這意味着它必須是一個static
緩沖區(然后被對該函數的任何后續調用所覆蓋,這會更早中斷)返回值)或由函數分配,在這種情況下,調用方負責釋放它。
您提到的scanf
在讀取交互式用戶輸入時也存在問題,例如,它可能會使輸入處於意外狀態,例如當您在一行的末尾不使用換行符時,對scanf
的下一次調用(可能是不相關的)函數)在遇到換行符時可能無法給出預期的結果。
將輸入逐行讀入緩沖區通常比較簡單,例如使用fgets
,然后從那里解析該行。 (某些輸入您可能可以簡單地通過逐個字符地讀取而無需緩沖區來解析,但是這樣的代碼通常很長且很難快速地執行。)
讀取任何可能包含除換行符以外的空格的字符串的示例如下:
/// 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
。 這種方法的優勢在於,調用方可以決定何時重用緩沖區以及是否需要復制字符串或僅讀取一次並忘記該字符串。
將Arkku的方法擴展為無限大小(實際上,它限制為SIZE_MAX -1個字符)作為輸入:
#include <stdlib.h>
#include <string.h>
#define BUFFER_MAX (256)
int read_string(FILE * pf, char ** ps)
{
int result = 0;
if (!ps)
{
result = -1;
errno = EINVAL;
}
else
{
char buffer[BUFFER_MAX];
size_t len = 0;
*ps = NULL;
while (NULL != fgets(buffer, sizeof buffer, pf))
{
len += strlen(buffer);
{
void * p = realloc(*ps, len + 1);
if (!p)
{
int es = errno;
result = -1;
free(*ps);
errno = es;
break;
}
*ps = p;
}
strcpy(&(*ps)[len], buffer);
}
if (ferror(pf))
{
result = -1;
}
}
return result;
}
這樣稱呼它:
#include <stdlib.h>
#include <stdlio.h>
int read_string(FILE * pf, char ** ps);
int main(void);
{
char * p;
if (-1 == read_string(stdin, &p)) /* This read from standard input,
still any FILE* would do here. */
{
perror("read_string() failed");
exit(EXIT_FAILURE);
}
printf("Read: '%s'\n", p);
free(p); /* Clean up. */
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.