How the C language receives arbitrary length strings entered by the keyboard

Source: Internet
Author: User

Sometimes you need to process the user input string, because you do not know in advance how long the user will enter a string, there are generally three kinds of processing methods:

1, according to estimate the user maximum input string length of the application space.

2, use Getch, scanf (%c), such as one character of a character receive processing.

3. Use

while (1)

{

scanf ("%1000s", &str);

....

Processing of STR strings

...

At the end

if (strlen (str)!=1000)//If the length is not 1000 instructions have been received, at this time can jump out of the loop

Break

}

The disadvantage of the first approach is that user input is likely to be longer than the programmer estimates. Application is small, will overflow, big waste.

The second method seems to be feasible, the processing of one character at a time, until it encounters a carriage return, but the efficiency is not high, each time you need to get data to the input cache of the system needs to consume more times.

The third method is the improvement of the second method, the longest time to obtain a string length of 1000, if the user input more than 1000, you can use the loop receive, each receive is saved in STR, no additional storage space.

Obviously, the third method is optimal.

How the C language receives arbitrary length strings entered by the keyboard

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.