Input string in C++

How to input a string whose number of characters we do not know using scanf in c++ ??

I got this question is discuss by some user posted in answer column… so I thought to move it to Q&A for help.

2 Likes

@rajvir007 You dont need the string length before for taking input of a string through scanf() and thats the advantage of scanf() function. Just use it like this:

char str[1000];
scanf("%s",str);

You can take input of a string of length upto 999 characters as last character is used for storing null character.

Also if you work in C++ which is far better and a good approach for beginners, you should use string data type like this:

string str;
cin>>str;

Remember scanf() can’t take input of string data type.
This has advantage of variable length you can have any length string input to it just only disadvantage is it is little slow compared to scanf().
I have upvoted your question which was posted in answers so that you can now ask question on your own. :slight_smile: Happy to help :slight_smile:

5 Likes

Just use scanf("%s", stringName); or cin >> stringName;

tip: If you want to store the length of the string while you scan the string, use this : scanf("%s %n", stringName, &stringLength);

stringName is a character array/string and strigLength is an integer.
Hope this helps. Happy Coding!

2 Likes

Hello,
scanf is faster than cin, but you could turn the iostream much faster just adding a simple line to your code

 std::ios::sync_with_stdio(false);

then the iostream is faster than scanf.

2 Likes

there are many ways to do this.

char s[1000];

cin>>s;

scanf(“%s”,&s);

gets(s);

The first two ways , there is a problem as it break the input at white spaces , meaning if the input string is “Hello World”, s takes the value “Hello”.

The third ways is safe , gets does not break at white spaces ,(all though it raises a compiler warning which you can ignore) and is faster than the first two methods.

Look into this link

1 Like

What are you trying to do? You could have posted a comment easily. This is ridiculous.

the moment i added this line of code in my program it printed 0 0 0 which was earlier working fine :frowning:

try not to use cin and scanf together when using std::ios::sync_with_stdio(false);
it creates synchronization problem

You can simply use cin >> stringname , you don’t need to know the number of characters.