+ 1

How can i take an string input of fixed length?

In c++ using string object I am taking an input of word but I am not able to take a fixed length string it is taking unlimited size string,no foundation. string STR; cin>>STR; or char s[4]; get(); etc. sghdfhd...... are possible why?

14th Dec 2016, 5:47 PM
RITESH KUMAR
RITESH KUMAR - avatar
5 Answers
+ 3
I can think of one C function, it is from library stdio.h.(You have to include it) fgets(char *string, int size, FILE *stream) In your case: #include <stdio.h> int main(){ char str[5]; fgets(str, 4, stdin); return 0; } If you want a string of size n, it is better to declare string of size n+1, because of \0 char.
14th Dec 2016, 9:21 PM
Martin BrezĂĄni
Martin BrezĂĄni - avatar
0
you r right but it is not able to stop string input on console after specified length.
14th Dec 2016, 9:59 PM
RITESH KUMAR
RITESH KUMAR - avatar
0
yes
14th Dec 2016, 10:19 PM
RITESH KUMAR
RITESH KUMAR - avatar
0
Due to some internet articles, it is not possible to disable user typing text. But maybe try to look for answer on internet. If you want just ignore other letters in row, use function: scanf("%d", input);
14th Dec 2016, 10:29 PM
Martin BrezĂĄni
Martin BrezĂĄni - avatar
0
ok thanks a lot
14th Dec 2016, 10:31 PM
RITESH KUMAR
RITESH KUMAR - avatar