【问题标题】:Input name with (whitespace) [closed]带有(空格)的输入名称[关闭]
【发布时间】:2016-05-11 05:21:31
【问题描述】:

谁能帮我写代码

void gotoxy(int, int);
void clrscr();
void dispMenu();

int main(void){
    int choice;

    choice = 0;
menu:
    dispMenu();
    scanf("%d", &choice);

    if(choice==1){
        clrscr();

        char name[100];

        printf("Please Input your Complete name: ");
        scanf("%[^\n]s", &name);

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

    getch();
    goto menu;
}

void dispMenu(){
    gotoxy(23,9);
    printf("List of C-Lang Activities\n");
    gotoxy(23,11);
    printf("1. Input Name");
    gotoxy(23,12);
    printf("2. (blank) \n");
    gotoxy(23,13);
    printf("3. (blank) \n");
    gotoxy(23,14);
    printf("4. (blank)\n");
    gotoxy(23,15);
    printf("5. (blank)\n");
    gotoxy(23,17);
    printf("Please Enter the Number of your choice: ");
}

void gotoxy(int x, int y){
    HANDLE hConsoleOutput;
    COORD dxCursorPosition;
    dxCursorPosition.X = x;
    dxCursorPosition.Y = y;

    hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(hConsoleOutput, dxCursorPosition);
}

void clrscr(){
    system("cls");
}

当我尝试将程序放入表格菜单时遇到问题:

输出会是这样的

Please Input your Complete Name: John Kenneth

Your Name is: John Kenneth

【问题讨论】:

  • scanf("%[^\n]s", &name); 不要在这里使用& 并且%[ 本身就是一个说明符,所以不要在它后面加上s。

标签: c removing-whitespace


【解决方案1】:

你的问题出在

scanf("%[^\n]s", &name);

它有两个问题:

  1. %[ 需要 char*,但您提供的是 char(*)[100]。
  2. s 不是 %[ 说明符的一部分。

解决这些问题,你得到

scanf("%[^\n]", name);

但您会注意到您再次获得相同的输出。这是因为如果要读取的第一个字符是 \n,%[^\n] 将失败。想知道这个角色是从哪里来的吗?记得在输入前一个scanf 的数字后按Enter 吗?这个字符在stdin 中占主导地位,使scanf("%[^\n]", name); 失败。

您也可以通过指示scanf 在读取之前丢弃/跳过所有空白字符来解决此问题,方法是在格式字符串之前添加一个空白字符,例如一个空格,如下所示:

scanf(" %[^\n]", name);

现在它会按预期工作。

请注意,最好通过使用长度说明符来限制scanf 读取的字符数,以便释放一些缓冲区溢出。这可以通过使用来完成:

scanf(" %99[^\n]", name);

我使用了 99,因为必须为字符串末尾的 NUL 终止符('\0')保留额外的空间。

另外,最好查看scanf的返回值,看是否成功:

if(scanf(" %99[^\n]", name) != 1)
    /* Input error or EOF */

【讨论】:

    【解决方案2】:

    使用标准函数fgets。例如

    fgets( name, sizeof( name ), stdin );
    name[strcspn( name, "\n" )] = '\0';
    

    考虑到使用 goto 语句是个坏主意。您应该忘记 C 中有 goto 语句。改用 while 或 do-while 循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多