如何告诉scanf在达到最大大小或一个“";输入“;点击了吗?

如何告诉scanf在达到最大大小或一个“";输入“;点击了吗?,c,C,我想索引一个单词,但如果输入的单词小于大小限制,我希望数组的大小根据该单词的大小进行更改。这是我的代码: #include <stdio.h> #define SIZE 10 int main(void) { int index; char wordToPrint[SIZE]; printf("please enter a random word:\n"); for (index = 0; index < SIZE; index++)

我想索引一个单词,但如果输入的单词小于大小限制,我希望数组的大小根据该单词的大小进行更改。这是我的代码:

#include <stdio.h>
#define SIZE 10
int main(void)

{
    int index;
    char wordToPrint[SIZE];
    printf("please enter a random word:\n");
    for (index = 0; index < SIZE; index++)
    {
        scanf("%c", &wordToPrint[index]);
    }
    for (index = 0; index < SIZE; index++)
    {
        printf("%c", wordToPrint[index]);
    }

    return 0;
}
#包括
#定义尺寸10
内部主(空)
{
整数指数;
char wordToPrint[大小];
printf(“请输入一个随机单词:\n”);
对于(索引=0;索引
我应该添加什么来定义它

tnx包括 #定义尺寸10 内部主(空) { 整数指数; //声明指向已分配空间的指针变量 char*wordToPrint; printf(“输入字符串最大值为10的大小”); scanf(“%d”和索引); 如果(索引>10){ printf(“超出允许限制”); }否则{ //调用malloc为数组分配适当数量的字节 wordToPrint=(char*)malloc(sizeof(char)*index);//分配 //使用[]符号访问数组存储桶 对于(i=0;i
动态内存分配只能通过malloc或calloc函数在c中完成。您可以要求用户输入最大大小,并检查是否超过允许的限制,否则您将获得具有用户输入值大小的数组,就像用户输入5您将获得大小为5字符的数组一样。

@谢谢,虽然我没有接触到fgets,而且在练习中需要scanf。如果你知道使用scanf的解决方案,我会很好:)如果你必须使用
scanf()
,请记住
scanf()
返回一个值,它可能会在
wordToPrintf[index]
中放入一些内容(因为这是你要求它做的)。您可以使用这些信息来确定是否按enter键。@MichaelBurr找到了!感谢allot:)如果你得到了他所说的,请将你的解决方案作为答案发布。如果你想更改数组的大小,你需要一个动态数组,最好是一些std容器
#include <stdio.h>
#define SIZE 10
int main(void)
{
    int index;

    // declare a pointer variable to point to allocated space
    char *wordToPrint;

    printf("enter the size of string MAX is 10");
    scanf("%d",&index);
    if(index > 10){ 
       printf("out of allowd limit");
    } else {

        // call malloc to allocate that appropriate number of bytes for the array
        wordToPrint= (char *)malloc(sizeof(char)*index);      // allocate

        // use [] notation to access array buckets
        for(i=0; i < index; i++) 
        {
           scanf("%c",&wordToPrint[i]);
        }
        for (i= 0; i< index; i++)
        {
           printf("%c", wordToPrint[i]);
        }
        free(wordToPrint);
    }

    return 0;
 }