string length

length
string

#1

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


#2

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


#3

@arshit you can use

In c:
char str[n+1];
gets(str);

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


#4

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.


#5

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[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);

#6

Try this. Read the explanation here.


#7

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


#8

thank u everybody!!


#9

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.


#10

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


#11

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


#12

Please accept answer, to close the thread.