我必须扫描一个带空格的字符串,这样我就可以在这种情况下用它做一些事情,将字符串向右或向左移动 n 个字符。例如:
如果我给 n = 1,则字符串
house
变成:
ehous
但输入也可以是带有空格的字符串,例如 n 相同:
yellow house
变成:
eyellow hous
所以要扫描字符串,我这样做:
char text[166];
scanf("%d %[^\n]%*c", &n, &text);
一切都很好,但现在我提交了程序,我收到了这个错误:
src.c: In function 'main':
src.c:30:26: error: format '%[^
' expects argument of type 'char *', but argument 3 has type 'char (*)[166]' [-Werror=format=]
30 | scanf("%d %[^\n]%*c", &nVezes, &texto);
| ~~~^~ ~~~~~~
| | |
| char * char (*)[166]
我有什么办法解决这个问题?我也不能使用这些库 string.h、strings.h 和 stdlib.h。
感谢您的每一点帮助。
答案 0 :(得分:1)
scanf()
不会真正扫描字符串,而是stdin
。
相反,OP 想要将用户输入的 行 读入 int
和 string。
省去麻烦 - ditch scanf()
有很多弱点。
// v---------------------- missing width limit
// v------- do not use here
scanf("%d %[^\n]%*c", &n, &text);
// ^ ^ ----------------------- possible to read more than 1 line
// return value not checked
使用 fgets()
@David C. Rankin
char text[166];
char line[sizeof text + 20];
if (fgets(line, sizeof line, stdin)) {
if (sscanf(line, "%d %165[^\n]", &n, text) == 2) {
Success(); // OP's code here
}
}
答案 1 :(得分:0)
您不需要将字符数组作为指针(*) 传递。在 C 中将数组作为参数传递给函数时,数组的名称充当指向数组开头的指针。
因此,您应该按如下方式传递数组:
scanf("%d %[^\n]%*c", &n, text);