【发布时间】:2015-07-28 02:15:26
【问题描述】:
我正在尝试编写一个执行以下操作的函数:
- 开始一个输入循环,每次迭代都打印
'> '。 - 获取用户输入的任何内容(未知长度)并将其读入字符数组,并在必要时动态分配数组的大小。用户输入的行将以换行符结束。
- 在字符数组的末尾添加一个空字节
'\0'。 - 当用户输入一个空行时循环终止:
'\n'
这是我目前写的:
void input_loop(){
char *str = NULL;
printf("> ");
while(printf("> ") && scanf("%a[^\n]%*c",&input) == 1){
/*Add null byte to the end of str*/
/*Do stuff to input, including traversing until the null byte is reached*/
free(str);
str = NULL;
}
free(str);
str = NULL;
}
现在,我不太确定如何将空字节添加到字符串的末尾。我在想这样的事情:
last_index = strlen(str);
str[last_index] = '\0';
但我不太确定这是否可行。我无法测试它是否可以工作,因为我在尝试编译代码时遇到了这个错误:
warning: ISO C does not support the 'a' scanf flag [-Wformat=]
那么我该怎么做才能让我的代码正常工作呢?
编辑:将 scanf("%a[^\n]%*c",&input) == 1 更改为 scanf("%as[^\n]%*c",&input) == 1 给我同样的错误。
【问题讨论】:
-
您不能使用
strlen来获取最后一个索引,假设您的字符串末尾没有空值。如果它最后确实有一个空值,那你为什么要重新添加它? -
input错字为str。
标签: c arrays user-input scanf dynamic-memory-allocation