在C中用scanf填充字符数组
如何用键盘填充空字符数组? 差不多在C中用scanf填充字符数组,c,C,如何用键盘填充空字符数组? 差不多 char a_string[]; while("if not Q") { printf("Enter a number: "); scanf("%c", a_string); } 我知道这是错误的 我只想知道如何在不限制大小的情况下为我的a_字符串[]赋值。 所以大小将根据我要从键盘输入的键数而变化 谢谢 试试这个: #include <stdlib.h> #include <stdio.h> int main() { ch
char a_string[];
while("if not Q")
{
printf("Enter a number: ");
scanf("%c", a_string);
}
我知道这是错误的
我只想知道如何在不限制大小的情况下为我的a_字符串[]赋值。
所以大小将根据我要从键盘输入的键数而变化
谢谢 试试这个:
#include <stdlib.h>
#include <stdio.h>
int main() {
char *string = NULL;
char *newstring = NULL;
char c = '\0';
unsigned int count = 0;
while(c != 'Q'){
c = getc(stdin);
if(string == NULL){
string = (char *) malloc(sizeof(char)); // remember to include stdlib.h
string[0] = c;
}
else{
newstring = (char *) realloc(string, sizeof(char)*count);
string = newstring;
string[count] = c;
}
count++;
}
string[count-1] = '\0'; // remove the Q character
fprintf(stderr,"here you are: %s",string);
free(string); // remember this!
return 0;
}
#包括
#包括
int main(){
char*string=NULL;
char*newstring=NULL;
字符c='\0';
无符号整数计数=0;
而(c!=“Q”){
c=getc(标准偏差);
if(字符串==NULL){
string=(char*)malloc(sizeof(char));//记住要包括stdlib.h
字符串[0]=c;
}
否则{
newstring=(char*)realloc(string,sizeof(char)*count);
字符串=新闻字符串;
字符串[计数]=c;
}
计数++;
}
字符串[count-1]='\0';//删除Q字符
fprintf(stderr,“给你:%s”,字符串);
自由(字符串);//记住这个!
返回0;
}
如果您在运行时开始时知道要输入多少个键,可以让它先询问键的数量,然后询问单个字符,如下面未测试的代码段所示
否则,您必须设置一些永远不会达到的实际最大值(例如10000),或者,如果不可能,请设置每个阵列的最大值,并为滚动到新阵列做好准备。最后一个选项实际上是相同的(最终由内存限制),但会给您一个更大的最大值
char *mychars;
int numchars;
printf("Please enter the total number of characters:\n");
if (scanf("%d", &numchars) == NULL) {
printf("couldn't read the input; exiting\n");
exit(EXIT_FAILURE);
}
if (numchars <= 0) {
printf("this input must be positive; exiting\n");
exit(EXIT_FAILURE);
}
mychars = (char *) malloc (numchars * sizeof(char));
int current_pos = 0;
printf("Enter a digit and hit return:\n");
while (scanf("%c", &mychars[current_pos]) != NULL && current_pos < numchars) {
current_pos++;
printf("Enter a digit and hit return:\n");
}
char*mychars;
国际货币基金组织;
printf(“请输入字符总数:\n”);
if(scanf(“%d”,&numchars)==NULL){
printf(“无法读取输入;正在退出\n”);
退出(退出失败);
}
if(numchars重复调用realloc()
将满足需要
根据需要加倍realloc()
大小以避免O(n)调用
代码可以执行最后的realloc(一个字符串,使用大小)
来修剪多余的内存分配。
调用例程需要在使用缓冲区时调用free()
。
以下是更干净的
int ch;
while((ch = fgetc(stdin)) != EOF && (ch != 'Q')) {
在C中无法按您希望的方式执行。缺少大小
int ch;
while((ch = fgetc(stdin)) != EOF && (ch != 'Q')) {