【问题标题】:C++, User input of letters, numbers, and spaces into a stringC++,用户将字母、数字和空格输入字符串
【发布时间】:2015-01-31 14:47:33
【问题描述】:

所以我有一个小问题,我找不到优雅的解决方案。

我要求用户输入他们的地址。我将如何将其放入字符串中?它将包含字母、数字和空格。我尝试了 getline 功能,但没有成功。

cout cin >> 地址;

【问题讨论】:

    标签: c++ string input


    【解决方案1】:

    你可以使用std::getline

    int main()
    {
        // greet the user
        std::string name;
        std::cout << "What is your name? ";
        std::getline(std::cin, name);
        std::cout << "Hello " << name << ", nice to meet you.\n";
    }
    

    【讨论】:

      【解决方案2】:

      要执行类似的操作,您需要使用 stringgetline

      string address;
      cout << "\nEnter customer street address: ";
      cin.ignore(numeric_limits<streamsize>::max()); // May or may not be needed.
      getline(cin, address);
      

      string Reference
      getline Reference numeric_limits Reference

      【讨论】:

      • 当我尝试 getline(cin, address);它只是跳过它并且没有得到用户输入,为什么?
      • @WhatThePhil,很奇怪,但请参阅我的编辑。这应该会照顾它。
      • @David 实际上当我使用 cin.ignore 时它对我不起作用(使用 onlinegdb C++17)
      【解决方案3】:

      就像说的:

        string address;
        cout << "\nEnter customer street address: ";
        getline(cin, address);
      

      有了这个你的输入可以输入,直到用户点击回车(换行);

      如果您想要多行输入,您仍然需要一些停止条件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-28
        • 1970-01-01
        • 2023-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多