
在C语言中,如何使用空格结束输入:使用scanf函数读取输入、使用getchar函数逐个读取字符、使用自定义函数处理空格。 为了详细描述,我们可以展开使用scanf函数读取输入这一点。
scanf函数是C语言中常用的输入函数,用于从标准输入读取数据。尽管scanf函数默认会忽略输入中的空格、制表符和换行符,但通过使用特定的格式控制符,我们可以让它读取并识别空格。具体而言,我们可以通过指定格式控制符 %[^n],这意味着读取所有字符直到遇到换行符,从而包括空格在内的所有字符都被读取进来。
一、使用scanf函数读取输入
1. 基础用法
在C语言中,scanf函数是非常强大的输入工具。它可以根据格式字符串读取和解析输入数据。为了读取包含空格的字符串,格式控制符 %[^n] 是非常有用的工具。这个控制符表示读取所有字符,直到遇到换行符为止。
#include <stdio.h>
int main() {
char input[100];
printf("Enter a string (use space to separate words): ");
scanf("%[^n]", input);
printf("You entered: %sn", input);
return 0;
}
在这个例子中,用户可以输入包含空格的字符串,直到按下回车键为止。整个输入字符串,包括空格,都将被存储在input数组中。
2. 读取多个输入
如果我们需要读取多个输入,每个输入以空格分隔,可以使用循环和scanf结合。例如:
#include <stdio.h>
int main() {
char input1[50], input2[50];
printf("Enter two strings separated by space: ");
scanf("%s %s", input1, input2);
printf("You entered: %s and %sn", input1, input2);
return 0;
}
在这个例子中,用户可以输入两个字符串,中间用空格分隔。scanf会自动将第一个字符串存储在input1,第二个字符串存储在input2。
二、使用getchar函数逐个读取字符
1. 基础用法
getchar函数是另一个读取输入的工具,它允许逐个字符地读取输入数据。我们可以使用getchar来逐个读取字符,直到遇到空格或其他特定字符为止。
#include <stdio.h>
int main() {
char ch;
printf("Enter a string (space to stop): ");
while ((ch = getchar()) != ' ') {
putchar(ch);
}
printf("nEnd of input.n");
return 0;
}
在这个例子中,程序会逐个读取字符并输出,直到遇到空格为止。
2. 处理多行输入
getchar函数还可以用于处理多行输入。例如,我们可以读取多行输入,直到遇到特定的结束条件。
#include <stdio.h>
int main() {
char ch;
printf("Enter text (type '.' to stop): ");
while ((ch = getchar()) != '.') {
putchar(ch);
}
printf("nEnd of input.n");
return 0;
}
在这个例子中,用户可以输入多行文本,直到输入.为止。
三、使用自定义函数处理空格
1. 基础用法
在某些情况下,可能需要自定义函数来处理输入中的空格。例如,可以编写一个函数来读取输入,直到遇到空格为止。
#include <stdio.h>
void readUntilSpace(char *buffer, int size) {
int i = 0;
char ch;
while (i < size - 1 && (ch = getchar()) != ' ' && ch != 'n') {
buffer[i++] = ch;
}
buffer[i] = '