首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用户在由空格分隔的一行中定义的字符串和int值

用户在由空格分隔的一行中定义的字符串和int值
EN

Stack Overflow用户
提问于 2019-10-12 17:02:52
回答 1查看 54关注 0票数 0

在我的家庭作业中,我的老师要我做计算谁欠的债最多的程序,他很难过,因为输入应该放在一条线上,例如:

安德鲁4

彼得5

在这里,我的问题是:如何在用空格分隔的一行上输入字符串和int值。

代码语言:javascript
运行
复制
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    //n is the number of names and k is number of how many debts i can delete but dont bother with that
    int n,k,SizeDebt;
    string str1;
    vector <string> Names;
    vector <int> Debt;

    do
    {
        cin >> n >> k;

    } while (n<1 || k>1000000);
    

    for (int i = 0; i < n; i++)
    {
        getline(cin, str1);
        cin >> SizeDebt;
        Names.push_back(str1);
        Debt.push_back(SizeDebt);
        
    }

    
    cin.get();
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-12 19:14:13

代码语言:javascript
运行
复制
#include <cstddef>
#include <cstdlib>

#include <iostream>
#include <string>
#include <utility>


int main()
{
    using namespace std;
    pair<size_t, string> max_debt {};

    size_t n, k, debt {};
    string name;

    // use k

    cin >> n >> k;

    // Integral types (Boolean, Character and Integer) implicitly converts to the bool. 
    // For integrals that aren't equal to 0 result of the conversion is true, else - false.
    // So, when we write --n, that means to compare whether n is equal to zero, and then decrement n.

    while (n-- && cin >> name && cin >> debt)    // answer
        if (debt > max_debt.first)
            max_debt = make_pair(debt, name);

    cout << max_debt.second << " has max debt – " << max_debt.first << endl;
    return EXIT_SUCCESS;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58356475

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档