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;
cin>>s;

[edit]
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];
gets(str);

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 != '\n'){
    str[len++]=ch;
    if(len==size){
        str = realloc(str, sizeof(char)*(size+=16));
        if(!str)return str;
    }
}
str[len++]='\0';

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

}

In main() function,

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

free(m);
1 Like

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];

cin>>a;

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];
fread(a,1,n,stdin);

‘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

1 Like

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

1 Like

Please accept answer, to close the thread.