【问题标题】:C++ String input in Vector [duplicate]Vector中的C ++字符串输入[重复]
【发布时间】:2021-03-25 06:37:32
【问题描述】:

我想将多字串输入向量"name"。使用 cin 对于单字输入效果很好。 我想要的是:

  1. 获取用户输入的字符串数。例如:“随机名称”
  2. 将所有字符串值存储到向量名称

这是我写的代码

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<string> names;
    string user;
    int n;
    cout << "Enter number of Users : ";
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> user;
        names.push_back(user);
    }
    for (int i = 0; i < names.size(); i++)
    {
        cout << names[i] << " ";
    }
}

问题: 当我在 for 循环中使用 getline() 而不是 cin 时,它会省略 1 个输入。 例如,如果用户输入 - Number of Users = 3,则只需要 2 个字符串输入

string user[n]; // value of n given by user using cin
for (int i = 0; i < n; i++)
{
    getline(cin, user[i]);
    names.push_back(user[i]);
}

【问题讨论】:

    标签: c++ string vector


    【解决方案1】:

    试试这个:

    #include <iostream>
    #include <vector>
    using namespace std;
    int main()
    {
        vector<string> names;
        string user;
        int n;
        cout << "Enter number of Users : ";
        cin >> n;
        for (int i = 0; i < n; i++)
        {
            cin >> std::ws;
            getline(cin,user);
            names.push_back(user);
        }
        for (int i = 0; i < names.size(); i++)
        {
            cout << names[i] << " ";
        }
    }
    
    cin>>std::ws;
    

    这里的问题是编译器在您输入输入数量并按回车后考虑换行符。因此,解决方法是提取额外的空格。检查http://www.cplusplus.com/reference/istream/ws/

    【讨论】:

    • 好答案。你只需要一个cin &gt;&gt; std::ws,所以你可以在循环之前完成它:cin &gt;&gt; n &gt;&gt; std::ws;
    • 是的...它工作...谢谢:)
    • 那么,这和 cin.ignore() 一样吗,因为 ignore() 也一样?任何用例都会有帮助
    猜你喜欢
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 2011-05-23
    • 1970-01-01
    相关资源
    最近更新 更多