简体   繁体   English

我如何在 c 中编写一个程序,显示不允许名字不超过 10 个字符?

[英]How do i write a program in c that show not allow first name not more than 10 characters?

I am trying to create a program to output firstname not more than 5 characters.我正在尝试创建一个程序来输出不超过 5 个字符的名字。

#include <stdio.h>
#include <stdlib.h>
int main()
{
     //declaring fisrtname
    char firstname[5];
    printf("Enter your name: ");
    scanf("%s", &firstname);
    printf("\nYour name: %s", firstname);
    return 0;
}

While running a program, i am getting this in my command prompt:在运行程序时,我在命令提示符中得到了这个:

Enter your name: newton

Your name: ←
Process returned 0 (0x0)   execution time : 4.719 s
Press any key to continue.

There are a couple of errors holding you up:有几个错误阻碍了你:

  • The parameter passed into scanf is the wrong type (you are passing a pointer to an array, but it is just expecting a pointer).传递给 scanf 的参数类型错误(您正在传递一个指向数组的指针,但它只是期望一个指针)。 I would change that line to:我会将该行更改为:
scanf("%s", firstname);
  • The scanf function will happily overflow your filename[5] buffer. scanf 函数会很高兴地溢出您的文件名 [5] 缓冲区。 The quick fix would be to just up the size of the buffer to something like 256. But to do it the right way you'll need to switch to using something like fgets (passing in stdin), or the likes.快速解决方法是将缓冲区的大小增加到 256 之类的大小。但是要以正确的方式做到这一点,您需要切换到使用fgets (传入 stdin)之类的东西。
  • To truncate the name to five characters, you will need to write '\\0' (the null terminator) to the sixth memory location in the buffer (again, make sure your buffer is large enough).要将名称截断为五个字符,您需要将 '\\0'(空终止符)写入缓冲区中的第六个内存位置(再次确保缓冲区足够大)。
filename[5] = '\0';

Here is a working version of your code:这是您的代码的工作版本:

#include <stdio.h>
#include <stdlib.h>
int main()
{
     //declaring fisrtname
    char firstname[256];
    printf("Enter your name: ");
    scanf("%s", firstname);
    firstname[5] ='\0';
    printf("\nYour name: %s", firstname);
    return 0;
}

In your program, your array firstname only has space for 5 characters including the terminating null character.在您的程序中,您的数组firstname只有5字符的空间,包括终止的空字符。 That means you can only store 4 other characters in it.这意味着您只能在其中存储4其他字符。

When writing newton into the array, you will be writing 7 characters (including the terminating null character) into the array, although it only has space for 5 characters.newton写入数组时,您将向数组写入7字符(包括终止空字符),尽管它只有5字符的空间。 This means that you are writing to the array out of bounds, causing undefined behavior .这意味着您正在越界写入数组,导致未定义行为

If you want to limit the number of characters that are written into the array to 5 characters (not including the terminating null character), then you should change the scanf format specifier from "%s" to "%5s" .如果要将写入数组的字符数限制为5字符(不包括终止空字符),则应将scanf格式说明符从"%s"更改为"%5s" However, in that case, you must also increase the size of the array from 5 to 6 characters, so that you also have space for the terminating null character:但是,在这种情况下,您还必须将数组的大小从5 6字符增加到6字符,以便为终止空字符留出空间:

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    char firstname[6];

    printf( "Enter your name: " );
    scanf( "%5s", firstname );

    printf( "Your first name is: %s", firstname );

    return 0;
}

However, using scanf for line-based user input is generally not recommended.但是,通常不建议将scanf用于基于行的用户输入。 It is usually better to use fgets instead.通常最好使用fgets代替。 See this guide for more information:有关更多信息,请参阅本指南:

A beginners' guide away from scanf() 远离 scanf() 的初学者指南

The %s format specifier of scanf will attempt to read exactly one word of input. scanf%s格式说明符将尝试准确读取输入的一个字。 It won't read a whole line of input.它不会读取整行输入。 And it won't read a whole first name, if the first name consists of several words.如果名字由几个单词组成,它不会读取整个名字。 For example, with the first name John Paul , the "Paul" is also part of the first name, not the middle or last name.例如,对于名字John Paul"Paul"也是名字的一部分,而不是中间名或姓氏。 Therefore, it is generally also important to read the second word of the first name.因此,阅读名字的第二个单词通常也很重要。

This can be best accomplished by reading a whole line of input using fgets :这可以通过使用fgets读取整行输入来最好地完成:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( void )
{
    char line[100];

    //prompt user for input
    printf("Enter your first name: ");

    //attempt to read one line of input
    fgets( line, sizeof line, stdin );

    //remove newline character, if it exists
    line[strcspn(line,"\n")] = '\0';

    //print input back to user
    printf( "Your first name is: %s\n", line );

    return 0;
}

If you want to limit the output to 5 characters, then you can change the line如果要将输出限制为 5 个字符,则可以更改行

printf("Your first name is: %s\n", line );

to:到:

printf("The first 5 characters are: %.5s\n", line );

If you instead only want to allow the user to enter up to 5 characters, and want to reject the input and prompt the user to enter valid input again, then you can do that too:如果您只想允许用户输入最多 5 个字符,并且想要拒绝输入并提示用户再次输入有效输入,那么您也可以这样做:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( void )
{
    char line[100];

    //this loop will run until the user enters valid input
    for (;;) //infinite loop, equivalent to while(1)
    {
        //prompt user for input
        printf("Enter your first name: ");

        //attempt to read one line of input
        fgets( line, sizeof line, stdin );

        //remove newline character, if it exists
        line[strcspn(line,"\n")] = '\0';

        //reject input if it is too long
        if ( strlen(line) > 5 )
        {
            printf( "Error: Input is too long!\n" );
            continue;
        }

        //input is ok, so break out of infinite loop
        break;
    }

    //print input back to user
    printf( "Your first name is: %s\n", line );

    return 0;
}

One problem with the code above is that it does not have any error handling.上面代码的一个问题是它没有任何错误处理。 It always assumes that the call to fgets will succeed and that the input will never be too large for the input buffer.它始终假设对fgets的调用会成功,并且输入对于输入缓冲区来说永远不会太大。 If any of these assumptions are false, then the program will misbehave.如果这些假设中的任何一个是错误的,那么程序就会运行不正常。

A more robust version of the code above would look like this:上面代码的一个更健壮的版本看起来像这样:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( void )
{
    char line[100];
    char *p;

    for (;;) //infinite loop, equivalent to while(1)
    {
        printf("Enter your first name: ");

        //attempt to read one line of input
        if ( fgets( line, sizeof line, stdin ) == NULL )
        {
            fprintf( stderr, "input error!\n" );
            exit( EXIT_FAILURE );
        }

        //find newline character
        p = strchr( line, '\n' );

        //verify that newline character was found
        if ( p == NULL )
        {
            int c;

            //check if unable to read whole line due to input failure
            if ( ferror( stdin ) )
            {
                fprintf( stderr, "input error!\n" );
                exit( EXIT_FAILURE );
            }

            //if end-of-file is encountered, then it is ok if
            //a newline character was not encountered
            if ( !feof(stdin) )
            {
                printf( "Error: Line was too long for input buffer.\n" );

                //discard remainder of line
                while ( ( c = getchar() != '\n' ) )
                {
                    if ( c == EOF )
                    {
                        fprintf(
                            stderr,
                            "input error discarding remainder of line!\n"
                        );
                        exit( EXIT_FAILURE );
                    }
                }

                //prompt user for new input
                continue;
            }
        }
        else // p != NULL
        {
            //discard newline character
            *p = '\0';
        }

        //verify that input satisfies our special requirements
        if ( strlen(line) > 5 )
        {
            printf( "Error: Input is too long!\n" );
            continue;
        }

        //input was ok, so we can break out of infinite loop
        break;
    }

    printf("Your first name is: %s\n", line );

    return 0;
}

This is what the output of the program looks like:程序的输出是这样的:

Enter your first name: Michael
Error: Input is too long!
Enter your first name: Jimmy
Your first name is: Jimmy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM