{"title":"C++ 中如何将带空格的字符串放入数组","description":"本文介绍了如何在 C++ 中使用 `std::getline()` 函数读取带有空格的输入并将其存储到字符数组中,并提供了一个示例代码。","keywords":"C++, 数组, 字符串, 空格, std::getline(), 输入, 输出, 代码示例","content":"在 C++ 中,可以使用 `std::getline()` 函数来读取带有空格的输入,并将其存储到数组中。以下是一个例子:\n\ncpp\n#include <iostream>\n#include <string>\n\nint main() {\n std::string input;\n std::cout << \"请输入带有空格的输入: \" ;\n std::getline(std::cin, input);\n\n // 创建数组a\n char a[666];\n \n // 将输入复制到数组a\n for (int i = 0; i < input.length(); i++) {\n a[i] = input[i];\n }\n \n // 输出数组a的内容\n std::cout << \"数组a的内容为: \" ;\n for (int i = 0; i < input.length(); i++) {\n std::cout << a[i];\n }\n \n return 0;\n}\n\n\n在上面的例子中,我们首先使用 `std::getline()` 函数读取带有空格的输入,并将其存储在 `std::string` 类型的变量 `input` 中。然后,我们创建一个大小为 666 的字符数组 `a`。接下来,我们使用一个循环将 `input` 中的字符逐个复制到数组 `a` 中。最后,我们输出数组 `a` 的内容。\n\n请注意,上述例子中的代码并没有对数组越界进行处理,所以在实际应用中需要根据具体情况进行处理。"}


原文地址: https://www.cveoy.top/t/topic/pOjF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录