string length



how to input a string of length n
where 1<=n<=100000 ?


in c

char s[n + 1];
scanf("%s", s);

in c++

string s;

for spaces using gets may be dangerous
better to use scanf with modifiers or write your own get() using getchar


@arshit you can use

In c:
char str[n+1];

In c++:
string str;
getline(cin, str);


You can better accept a single character using a getchar() and make your string the way, str[idx++] = c; where c was your i/p till you find your ending character.


The safer and better way to implement it is using Dynamic Arrays - realloc() !

char *enterString(FILE* fp, size_s strs)
char *str;
int ch;
size_s len = 0;
str = realloc(NULL, sizeof(char)*strs);
if(!str)return str;
while(EOF!=(ch=fgetc(fp)) && ch != '

str = realloc(str, sizeof(char)*(size+=16));
if(!str)return str;

return realloc(str, sizeof(char)*len);


In main() function,

s = enterString(stdin, 10);
printf("%s", s);



Try this. Read the explanation here.


@arshit the best and easy way to do it is :

In C:-

char a[100000];

scnaf("%s",&a); or gets(a);

In C++ :-

char a[100000];



thank u everybody!!


If you are sure about the value of n, i.e. you know for sure the number of characters forming the string,the fread is the appropriate function to use. It picks the next n characters from the stream with no regard to any sort of whitespaces(space,newline,tab etc).This means it picks them all. The syntax is-

char a[n];

‘a’ is the data array.
‘1’ is the size in bytes of the data block you are storing in a.
‘n’ is the number of data blocks to pick.
‘stdin’ can be used interchangeably with whatever stream you are using.


Neither of the approaches will work if the string contains an embedded space


we need to take care of the fact that gets() leave a ’
’ character in the i/p stream and getline doesnot.


Please accept answer, to close the thread.