0

我在 C 中有这个简单的代码来扫描和打印带有空格的字符串:

#include <stdio.h>
#include <string.h>
int main()
{
   char myName[50];
   printf("Enter your name: ");
   scanf("%[^\n]s", &myName);
   printf("Your name is: %s", myName);
   return 0;
}

编译器(gcc,我的 Mac 上 Xcode 附带的命令行工具的一部分)返回此错误:

name.c: In function ‘main’:
name.c:7: warning: format ‘%[^
’ expects type ‘char *’, but argument 2 has type ‘char (*)[50]’
name.c:7: warning: format ‘%[^
’ expects type ‘char *’, but argument 2 has type ‘char (*)[50]’

这里有什么问题?

注意:我需要使用 scanf。我没有 fgets :(

4

5 回答 5

4

您应该传递给scanf类型的参数char*(格式%[^\n]s期望如此),但在您的代码中:

char myName[50];
scanf("%[^\n]s", &myName);

你传递一个myName数组地址(即char (*)[50])。您应该将其更改为:

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

或者:

scanf("%[^\n]", &myName[0]);
于 2013-09-27T20:20:13.960 回答
2

Couple issues

  1. Wrong scanf() format s. The s is not part of the format specifier. The %[] format specifier ends with the ].

  2. Wrong scanf() parameter &myName. Rather than passing the address of &myName, which is type char (*)[50] , simply use myName. This will pass the address of the first element of myName which is a char *, the expected matching type for %[].

Use

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

Further recommend to consume leading white space and limit text read. The 49 limits the input to 49 characters, leaving 1 more byte for the terminating \0.

scanf(" %49[^\n]", myName);
于 2013-09-27T20:18:16.443 回答
2

这里有什么问题?

好吧,这里是:

format expects type ‘char *’, but argument has type ‘char (*)[50]’

指向数组的指针与指向数组第一个元素的指针不同。你应该摆脱那个&运营商。

于 2013-09-27T20:18:42.343 回答
1

In C, myName (when passed to a function) decays to a pointer to the first element of array (myname) of characters. &myName is a pointer to the array myname. &myName[0] would be a pointer to the first character, which is correct, but looks like you tried stuff at random until you chanced on something that worked.

于 2013-09-27T20:18:12.660 回答
0

您的问题是您将地址传递给字符串开头的指针,而不是指向字符串的指针。简单地说,删除&.

   scanf("%[^\n]", myName);
于 2013-09-27T20:20:16.453 回答