使用 'std::cin' 输入带有空格的字符串时,需要使用 'std::getline' 函数来读取整行输入,而不是使用 '>>' 运算符。

以下是一个示例,演示如何使用 'std::getline' 和 'std::cin' 来输入带有空格的字符串:

#include <iostream>
#include <string>

int main() {
    std::string sentence;

    std::cout << "Enter a sentence: ";
    std::getline(std::cin, sentence);

    std::cout << "You entered: " << sentence << std::endl;

    return 0;
}

在这个示例中,我们使用 'std::getline' 函数从标准输入流 'std::cin' 中读取整行输入,并将其存储在字符串 'sentence' 中。

请注意,在使用 'std::getline' 函数时,需要提供两个参数:输入流对象和字符串变量。输入流对象是 'std::cin',而字符串变量是用来存储输入的字符串。

通过使用 'std::getline' 函数,我们可以读取包含空格的整行输入,而不会在空格处停止读取。

希望以上示例能够帮助你使用 'std::cin' 输入带有空格的字符串!如果你还有其他关于输入输出或 C++ 的问题,请随时提问。

C++ 使用 cin 输入带空格的字符串

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

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