在 C 语言中,可以使用 scanf() 函数从字符串中读入数字和字母。1. 读入数字: (1)如果数字用空格分隔,使用 %d 格式说明符。 (2)如果数字不分隔,使用 %d 并指定宽度。 2. 读入字母: (1)使用 %c 读入单个字符。 (2)使用 %s 读入字符串(直到空格)。

如何从字符串中读入数字和字母(C 语言)
在 C 语言中,我们可以使用 scanf() 函数从字符串中读入数字和字母。
读入数字:
如果字符串中包含空格分隔的多个数字,可以使用 %d 格式说明符:
立即学习“C语言免费学习笔记(深入)”;
<code class="c">#include <stdio.h>
int main() {
char str[] = "10 20 30";
int num1, num2, num3;
scanf(str, "%d %d %d", &num1, &num2, &num3);
printf("%d %d %d\n", num1, num2, num3);
return 0;
}</code>如果字符串中不包含空格分隔,可以使用 %d 格式说明符并指定宽度:
<code class="c">#include <stdio.h>
int main() {
char str[] = "102030";
int num;
scanf("%3d", &num); // 读取 3 个字符作为数字
printf("%d\n", num);
return 0;
}</code>读入字母:
使用 %c 格式说明符读入单个字符:
<code class="c">#include <stdio.h>
int main() {
char str[] = "Hello";
char ch;
scanf(str, "%c", &ch); // 读入第一个字符
printf("%c\n", ch);
return 0;
}</code>使用 %s 格式说明符读入字符串(直到遇到空格):
<code class="c">#include <stdio.h>
int main() {
char str[] = "Hello World";
char word[20];
scanf(str, "%s", word); // 读入第一个单词
printf("%s\n", word);
return 0;
}</code>以上就是c语言怎么读入字符串中的数字和字母的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号