c++ - 字符串中的空格是否会改变程序对它的解释方式?

标签 c++

我正在努力学习 C++。我创建了一个输入名称然后说“你好,<名称>!”的程序。但是当我输入“Aditya Singh”作为名称时,它输出“Hello, Aditya!”,这不是我所期望的。

我的代码:

#include <iostream>
#include <string>

using namespace std;

// I created the class because I was learning C++ Classes
class MyClass {
public: 
    void setName(string inp) {
        name = inp;
    }
    string getName() {
        return name;
    }

private:
    string name;
};

int main() {
    // Input Name

    string inpName;
    cout << "Please enter your name\n";
    cin >> inpName;

    // Say hello

    MyClass name;
    name.setName(inpName);
    cout << "Hello, " << name.getName() << "!" << endl;
}

发生这种情况是因为字符串中有空格吗?那么如何输出带有空格的字符串呢?

最佳答案

这是因为 cin >> inpName 一次读取一个单词,所以是的,这是因为输入中的空格。看来您需要的是一种读取换行符 \n 之前的机制。此功能已经存在,只需将 cin >> inpName 替换为

std::getline(cin, inpName); // Store everything until \n in inpName

关于c++ - 字符串中的空格是否会改变程序对它的解释方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55648393/

相关文章:

c++ - xcode 在哪里保留其库和 header 的默认路径?

c++ - 读取可能不完整的文件 C++

c++ - 为 std::index_sequence 使用默认参数

c++ - 为什么堆栈上分配了这么多空间?

c++ - 没有对 std::index_sequence 中的包扩展进行诊断

c++ - 有人曾经将 boost::singleton 与 boost::logger 一起使用过吗?

c++ - std::swap 返回 0xBAADF00D

c++ - 列出线程 C++

c++ - “is not required” ==未定义行为?

C++ 检查 2 个数组中的相同值