while循环输入字符串
时间: 2023-10-24 15:06:42 浏览: 192
使用while循环输入字符串的方法如下:
```
prompt = "请输入一些文字,输入'quit'结束程序:"
message = ""
while message != 'quit':
message = input(prompt)
print(message)
```
这个程序会不断地提示用户输入文字,直到用户输入'quit'为止。每次用户输入文字后,程序都会将其打印出来。
相关问题
while循环中字符串输入
在while循环中,我们可以使用input()函数来获取用户输入的字符串。为了让循环一直运行,我们可以使用while True语句。在循环中,我们可以使用if-elif-else语句来检查用户输入的字符串是否等于我们想要的字符串。如果是,我们可以打印出相应的字符串并使用break语句来终止循环。下面是一个示例代码:
```python
while True:
user_input = input("请输入y或n:")
if user_input.lower() == "y":
print("你输入了y")
break
elif user_input.lower() == "n":
print("你输入了n")
break
else:
print("请重新输入")
```
fgets循环输入字符串
fgets循环输入字符串的过程如下:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char buff[10];
while (fgets(buff, sizeof(buff), stdin) != NULL) {
printf("%s", buff);
}
return 0;
}
在这个例子中,使用fgets函数循环读取字符串,直到遇到文件结束符EOF。fgets函数会将输入数据保存在缓冲区中,并且会自动在字符串末尾添加一个换行符'\n'。所以在输出时,我们需要使用printf函数而不是puts函数来打印字符串,以保持与fgets读取的字符串一致。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)