×

# Input string in C++

 1 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. asked 31 Mar '16, 11:36 3★jain_mj 372●1●1●9 accept rate: 25% What are you trying to do? You could have posted a comment easily. This is ridiculous. (31 Mar '16, 12:24) ash_code3★

 1 @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. :) Happy to help :) answered 31 Mar '16, 11:45 3★jain_mj 372●1●1●9 accept rate: 25%
 0 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! answered 31 Mar '16, 11:56 3★ash_code 475●1●14 accept rate: 15%
 0 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. answered 31 Mar '16, 15:04 1★nuboro 71●3 accept rate: 0%
 0 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 answered 01 Apr '16, 11:56 439●14 accept rate: 16%
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×1,912
×643
×169

question asked: 31 Mar '16, 11:36

question was seen: 15,744 times

last updated: 01 Apr '16, 11:56