在C中动态读取用户输入字符串

时间:2016-07-05 20:08:11

标签: c

给定未知长度的用户输入(由最大长度为100的单词组成)。有没有办法逐字符串地动态读取它?

据我所知,scanf读取一个字符串直到达到一个空格,所以我尝试使用scanf,但它进入了一个无限循环。

char buf[101];
while (scanf("%s", buf))
{
    //something is done with the string
}

4 个答案:

答案 0 :(得分:4)

  

如果用户输入未知长度(包含最大长度为100的单词),有没有办法按字符串动态读取它?

构建自己的函数而不是scanf将有助于实现此目标

  • 在这里,我创建了一个函数scan,通过在每次迭代中增加它的大小来动态接收字符串

  • 由于以下原因,我使用了其他标题文件string.hstdlib.h

    1. stdlib.h 中的函数(点击了解更多)库文件对内存的动态分配非常有用。

    2. string.h 中的函数(点击了解更多)库文件可用于处理字符串

  

注意:来自用户的输入在他输入字符串end时停止。

#include <stdio.h>  //the standard library file
#include <stdlib.h> //library file useful for dynamic allocation of memory
#include <string.h> //library file with functions useful to handle strings

//the function    
char* scan(char *string)
{
    int c; //as getchar() returns `int`
    string = malloc(sizeof(char)); //allocating memory

    string[0]='\0';

    for(int i=0; i<100 && (c=getchar())!='\n' && c != EOF ; i++)
    {
        string = realloc(string, (i+2)*sizeof(char)); //reallocating memory
        string[i] = (char) c; //type casting `int` to `char`
        string[i+1] = '\0'; //inserting null character at the end
    }

    return string;
}

int main(void)
{
    char *buf; //pointer to hold base address of string

    while( strcmp((buf=scan(buf)),"end") ) //this loop will continue till you enter `end`
    {
        //do something with the string

        free(buf); //don't forget to free the buf at the end of each iteration
    }

    free(buf); //freeing `buf` for last input i.e, `end` 

}
  

让我们//do something with the string看看上面的代码是否有效:)

我在main函数中更改了以下while循环:

    while( strcmp((buf=scan(buf)),"end") )
    {
        //do something with the string
    }

while( strcmp((buf=scan(buf)),"end") )
{
    printf("you entered : %s\n",buf);
    printf("size        : %u\n",strlen(buf));
    printf("reversing   : %s\n",strrev(buf));

    printf("\n-------------------\n");

    free(buf);
}

现在,

输入:

hall
of
fame
stay in it
end

输出

you entered : hall
size        : 4
reversing   : llah

-------------------
you entered : of
size        : 2
reversing   : fo

-------------------
you entered : fame
size        : 4
reversing   : emaf

-------------------
you entered : stay in it
size        : 10
reversing   : ti ni yats

-------------------

答案 1 :(得分:0)

我认为你需要这样的东西。

while (scanf("%s", code) == 1)
{
    // no need for second scanf call
    // do whatever you like here
}  

编辑:试试这个。

freopen("input.txt","r",stdin);
//Above line makes program to take input from file.
//File should be present in same folder
char c[50];
while(scanf("%s",c)!=EOF)
{
    printf("%s\n",c);
}

答案 2 :(得分:0)

我找到了解决方案!

while (scanf("%s%c", buf, &c))
    {
        //do something with the string
        if (c == '\n') break;
    }

答案 3 :(得分:0)

如果有人仍然感兴趣,我不知道它是对还是错,但这对我来说很好。您也可以使用realloc和一个简单的。

char *st()
{
    int c, counter = 0;
    char a, *temp = NULL, *array = NULL;
    for (int i = 0; c = getchar(); i++, counter++)
    {
        if (c == 10)
            break;
        a = c;
        switch (counter % 2)
        {
            case 1: array = (char*)malloc((counter + 2) * sizeof(char));
                for (int j = 0; j < counter; j++)
                    array[j] = temp[j];
                free(temp);
                    array[i] = a;
                    array[i + 1] = '\0';
                break;
            case 0: temp = (char*)malloc((counter + 2) * sizeof(char));
                for (int j = 0; j < counter; j++)
                    temp[j] = array[j];
                free(array);
                    temp[i] = a;
                    temp[i + 1] = '\0';
                break;
        }
    }
    if (counter % 2)
        return temp;
    else
        return array;
}
int main()
{
    char *a = st();
    free(a);
    return 0;
}
相关问题