C++如何从键盘上输入一句话存到list容器中
时间: 2024-05-15 20:16:28 浏览: 8
以下是一个示例代码,可以从键盘上输入一句话,将其存储到 list 容器中:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <limits.h>
#define MAX_LINE_LENGTH 1024
int main() {
char line[MAX_LINE_LENGTH];
fgets(line, MAX_LINE_LENGTH, stdin); // 从标准输入中读取一行字符串
line[strcspn(line, "\n")] = '\0'; // 将换行符去掉
char *word = strtok(line, " "); // 使用空格分割字符串,获取每个单词
list<string> words; // 声明一个 list 容器
while (word != NULL) {
words.push_back(word); // 将单词添加到 list 容器中
word = strtok(NULL, " "); // 继续获取下一个单词
}
// 打印 list 容器中的所有单词
for (auto it = words.begin(); it != words.end(); it++) {
printf("%s\n", it->c_str());
}
return 0;
}
```
该代码使用 `fgets` 函数从标准输入中读取一行字符串,然后使用 `strtok` 函数将字符串按照空格分割成多个单词,逐个将单词添加到 list 容器中。最后,使用迭代器遍历 list 容器,打印出其中的所有单词。