c 语言输入不定数目个字符
时间: 2023-11-11 17:07:56 浏览: 48
可以使用循环读取输入,直到读取到换行符为止,例如:
```
#include <stdio.h>
int main() {
char c;
do {
scanf("%c", &c);
printf("%c", c);
} while (c != '\n');
return 0;
}
```
这个程序将不断读取输入的字符,并将其打印出来,直到读取到换行符为止。可以用 Ctrl+D(在 Windows 上是 Ctrl+Z)来结束输入,或者直接键入换行符(Enter 键)。
相关问题
c 语言输入已知数量字符串,每个分别存放
在不同的字符数组中,然后将它们按照字典序从小到大排序输出。
可以使用strcmp函数进行字符串比较,然后使用冒泡排序或者快速排序等算法进行排序。具体实现如下:
```c
#include <stdio.h>
#include <string.h>
#define MAX_STR_NUM 100
#define MAX_STR_LEN 100
void bubble_sort(char str[][MAX_STR_LEN], int n)
{
int i, j;
char temp[MAX_STR_LEN];
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (strcmp(str[j], str[j + 1]) > 0) {
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
}
}
int main()
{
char strs[MAX_STR_NUM][MAX_STR_LEN];
int n, i;
printf("请输入字符串的数量:");
scanf("%d", &n);
printf("请输入%d个字符串,每个字符串长度不超过%d个字符:\n", n, MAX_STR_LEN - 1);
for (i = 0; i < n; i++) {
scanf("%s", strs[i]);
}
bubble_sort(strs, n);
printf("按照字典序从小到大排序后的字符串为:\n");
for (i = 0; i < n; i++) {
printf("%s\n", strs[i]);
}
return 0;
}
```
这里使用了冒泡排序算法,也可以使用快速排序等其他排序算法。
c 语言scanf输入字符串
你可以使用`scanf`函数来输入字符串,它的格式化字符串为`%s`。以下是一个示例:
```c
#include <stdio.h>
int main() {
char str[100];
printf("请输入字符串:");
scanf("%s", str);
printf("你输入的字符串是:%s\n", str);
return 0;
}
```
在这个示例中,`scanf`函数会读取用户输入的字符串,并将其存储在`str`数组中。请注意,`scanf`函数默认以空格作为字符串的结束符,所以如果输入的字符串中有空格,`scanf`只会读取第一个空格之前的部分。如果你想读取整行字符串,可以使用`fgets`函数。