[英]How to limit size of user inputted string or dynamically allocate memory
所以我有這段代碼:
void main()
{
char word[21]={0}; // changed from 20 to 21 because of '\0'.
// do {
scanf("%s", &word);
// } while (strlen(niz)>20); this line is useless because program crashes anyway
}
問題:問題是我想將用戶想要輸入的字符數限制為20個。當然,我可以為word []保留更多的內存,但是如果我超過一定的數量,程序將再次崩潰。 您如何在C中解決這個問題?
問題:有什么方法可以在用戶輸入字符串后立即為字符串分配所需的內存。 例如,如果用戶輸入長度為999的字符串,我可以分配sizeof(string)* strlen(word)+ 1個字節的內存嗎?
注意:如果strlen()超過一定限制,我想提示用戶再次輸入新字符串。
您可以使用fgets
限制字符串長度:
fgets(word, sizeof(word), stdin);
對於第二部分:
不幸的是,在C語言中,您無法分配所輸入字符串所需的確切內存量。 原因是在為它分配內存之前,您需要知道字符串的長度,為此,您必須將該字符串存儲在緩沖區中。
如果要輸入任意大小的字符串並同時節省內存,請使用realloc
。
測試程序:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *s = malloc(1);
printf("Enter a string: \t"); // It can be of any length
int c;
int i = 0;
do
{
c = getchar();
s[i++] = c;
s = realloc(s, i+1);
}while(c != '\n' && c != EOF);
s[i] = '\0';
printf("Entered string: \t%s", s);
return 0;
}
有些版本的scanf
支持m
修飾符。 例如在glibc> = 2.7中。 它們為用戶分配必要的緩沖區:
char *p;
int n = scanf("%ms", &p);
if (n == 1) {
printf("read: %s\n", p);
free(p);
} else {
// error
}
還有a
較舊a
修飾符,其作用相同。
將%s中的字符常量放在s前面:
scanf("%20s", &word);
您的第二個問題:簡而言之,您需要存儲空間來接受輸入。 但是,減少分配的一種常見解決方案是執行以下操作:
char tmp[1000];
char *strptr;
scanf("%s", &temp);
strptr = malloc(sizeof(char)*(strlen(tmp)+1));
但這只會為您節省空間,如果您多次調用此函數1000次。
您可以改為使用fgets來限制輸入。
fgets(word, sizeof(word), stdin);
如果以后需要從字符串中提取內容,請使用sscanf
使用命令行參數.. main(int argc,char * argv [])
在這里argc將告訴您在提供可執行文件時傳遞了多少個參數。
argv將為您提供數據或字符串。只需將其提供給'char *'。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.