阅读未知长度从控制台的字符串 [英] Reading in a string of unknown length from the console

查看:133
本文介绍了阅读未知长度从控制台的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想读命令行任意长度的字符串,什么是要去关于它的最好方法是什么?

If I want to read in a string of arbitrary length from the command line, what's the best way of going about it?

目前,我这样做:

char name_buffer [ 80 ];
int chars_read = 0;
while ( ( chars_read < 80 ) && ( !feof( stdin ) ) ) {
   name_buffer [ chars_read ] = fgetc ( stdin );
   chars_read++;
}

但如果字符串长度超过80个字符我该怎么办?很显然,我可以在阵列初始化只是一个更大的数字,但我敢肯定,必须有一个更好的方法来给数组更多的空间使用malloc或东西吗?

But what can I do if the string is longer than 80 characters? Obviously I could just initialise the array to a bigger number but I'm sure there must be a better way to give the array more space using malloc or something?

任何提示将是巨大的。

推荐答案

发现不久前,在网上这个地方的真正有用的:

Found this somewhere on the net long ago, its really useful:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned int len_max = 128;
    unsigned int current_size = 0;

    char *pStr = malloc(len_max);
    current_size = len_max;

    printf("\nEnter a very very very long String value:");

    if(pStr != NULL)
    {
    int c = EOF;
    unsigned int i =0;
        //accept user input until hit enter or end of file
    while (( c = getchar() ) != '\n' && c != EOF)
    {
        pStr[i++]=(char)c;

        //if i reached maximize size then realloc size
        if(i == current_size)
        {
                        current_size = i+len_max;
            pStr = realloc(pStr, current_size);
        }
    }

    pStr[i] = '\0';

        printf("\nLong String value:%s \n\n",pStr);
        //free it 
    free(pStr);
    pStr = NULL;


    }
    return 0;
}

这篇关于阅读未知长度从控制台的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆