如何在c中正确printf整数和字符串?
我有以下代码:
char *s1, *s2; char str[10]; printf("type a string: "); scanf("%s", str); s1 = &str[0]; s2 = &str[2]; printf("%s\n", s1); printf("%s\n", s2);
当我运行代码时,输入输入“A 1”如下:
type a string: A 1
我得到以下结果:
A <
我正在尝试将第一个字符作为字符串读取,将第三个字符作为整数读取,然后在屏幕上打印出来。 第一个角色总是有效,但屏幕只会在那之后显示随机的东西….我该如何解决?
谢谢
你走在正确的轨道上。 这是一个更正版本:
char str[10]; int n; printf("type a string: "); scanf("%s %d", str, &n); printf("%s\n", str); printf("%d\n", n);
让我们来谈谈变化:
- 分配一个int(
n
)来存储你的号码 - 告诉
scanf
首先读取一个字符串,然后读一个数字(%d
表示数字,正如您从printf
已经知道的那样
这就是它的全部内容。 你的代码仍然有点危险,因为任何超过9个字符的用户输入都会溢出str
并开始践踏你的堆栈。
scanf("%s",str)
仅扫描,直到找到空白字符。 使用输入"A 1"
,它将仅扫描第一个字符,因此s2
指向恰好位于str
中的垃圾,因为该数组未初始化。
试试这个代码我的朋友……
#include int main(){ char *s1, *s2; char str[10]; printf("type a string: "); scanf("%s", str); s1 = &str[0]; s2 = &str[2]; printf("%c\n", *s1); //use %c instead of %s and *s1 which is the content of position 1 printf("%c\n", *s2); //use %c instead of %s and *s3 which is the content of position 1 return 0; }