Typically, performance arrays of sufficiently large static sizes, such as 999 cells, are used. Still, in C++ has a high-level feature: flow (stream). Streams allow you to add values slowly, with no size worries (apart from architecture support). Use of class stringstream
(in the library <sstream>
) allows to form and then generate a structure string
, this can be seen as a const char*
.
In C, I think stream would have to be implemented by hand. There are several ways to do this. Another option you have is to control the lifespan of the data, including using blocks to limit the lifespan of local variables. So, you can create an awesome size array, copy it to a smaller one and delete it. So for example.
# include <stdio.h>
# include <stdlib.h>
int main( int argCount , char **argVector ){
int tamanhoDoNome , indice ;
char *nome ;
{
char nomeTemporario[999] = {0} ;
cout << "Informe seu nome completo: " << endl ;
fgets( nomeTemporario , 998 , stdin ) ;
for( tamanhoDoNome=0 ; nomeTemporario[tamanhoDoNome++] ; ) ;
nome = malloc( tamanhoDoNome*sizeof(char) ) ;
for( indice=0 ; indice<tamanhoDoNome ; indice++ ) nome[indice]=nomeTemporario[indice] ;
}
// Agora não existem mais nomeTemporario e suas células, ficou nem a carcaça de sobra.
free( nome ) ;
// Agora não existem mais as células de nome, só existe a variável, ficou só a carcaça!
return 0 ;
}
Any doubt?
You want to create a string of arbitrary size. For this, you need to use pointers. I recommend putting in a class so that you can hide the implementation, with methods to increase or decrease the size of the allocated string as you need it
– Jefferson Quesado
With
getchar
andrealloc
can do well, but it involves building some logic. In your case I think it best to define a wider size, such as256
for example and just use this. Would it be awesome to read a name with 50,000 characters for example ? And how would I show it in the program ? Similarly note that databases, places where information such as thenome
are stored, has limit in the same, going thevarchar
to the limit of255
characters. Even a type liketext
, which supposedly represents unlimited text is also limited to 64KB.– Isac
Related https://answall.com/q/106719/101
– Maniero