Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include "stdio.h"
void main()
{
	char a[20];
	scanf("%s",a);
	printf("%s",a);
}


I want to input less than 20 characters, how to control the number I input?
if the number is more than 20, the program should give me a warn, I want to know how to do this,Thank you.
Posted

With scanf() and strings, you should always pass the width to specify the max. number of chars to be stored (pass one less than the size of the char array to store the terminating NULL char). So with max. 20 chars use:
C++
char a[21];
scanf("%20s",a);

To get the number of chars entered, use the strlen() function afterwards. To show a warning when too much chars has been entered, allow one more character to be scanned and compare the final string length:
C++
char a[22];
scanf("%21s",a);
if (strlen(a) > 20)
{
    // show warning here
}
 
Share this answer
 
Comments
CPallini 14-Dec-12 7:28am    
5 from 'fast' Carlo :-)
Espen Harlinn 17-Dec-12 12:36pm    
5'ed!
You may use the width specifier (see the security note in the MSDN documentation[^]), e.g.
C++
scanf("%19s",a);


(and always check scanf result)
 
Share this answer
 
v2
Comments
Jochen Arndt 14-Dec-12 6:52am    
+5. Beat me by a minute.
Angela2012 14-Dec-12 20:03pm    
Thank you ,but I want to know if it is possible to check the number of characters automatically using scanf,when the number is larger than 20,it will give me a warn immediately rather than I finish inputting a very very long string.
CPallini 15-Dec-12 4:58am    
No, it is not possible.
Mohibur Rashid 15-Dec-12 5:16am    
it is not possible with scanf is true
Espen Harlinn 17-Dec-12 12:36pm    
5'ed!
 
Share this answer
 
Comments
CPallini 14-Dec-12 7:29am    
5, even if you're advertising 'The Competitors' :-)
Thanks a lot @CPallini.
C++
#include <stdio.h>
#include <string.h>

void main()
{
	char a[20];
        int i, c=1;
        while(c == 1)
        {
              if(strlen(a) > 19)
              {
                   printf("WARNING\n");
                   printf("DANGER FOR BUFFER OVERFLOW");
              }
              printf("Give the next char: ");
	      scanf("%s", &a[i]);
	      printf("Scanned char: %c\n",a[i]);
              printf("If you want to input another char type 1 or type another number to exit");
              scanf("%d", &c);
              i++;
        }
}
 
Share this answer
 
v2
Comments
Angela2012 14-Dec-12 19:53pm    
Thank you very much,in your solution "strlen(a)" is always larger than 19
Snk Tay 15-Dec-12 5:11am    
strlen(a) is not always larger than 19. Because the array a[20] is empty at the begining and the lefth of array getting bigger when you add a char.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900