如何从字符串中读入数字和字母(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>
