while循环,直到用户停止提供输入

时间:2020-08-30 09:11:31

标签: c++

我正在练习竞争性编程。那里我面临一个问题。该问题没有任何特定的输入限制,也没有退出特定的输入。这是输入格式。

Input Format

Each line contains two integers,   A and B. One input file may contain several pairs  P.

Output Format

Output a single integer per line - The sum of A and B.

样本输入

1 2
2 5
10 14

样本输出

4
7
24

我需要帮助退出程序。

问题陈述: https://www.hackerearth.com/practice/basic-programming/complexity-analysis/time-and-space-complexity/practice-problems/algorithm/a-b-4/description/

2 个答案:

答案 0 :(得分:2)

只需执行以下操作即可读取输入内容:

int main() {
    int a, b;
    while(std::cin >> a >> b)
        std::cout << a + b << '\n';
}

顺便说一句,问题不仅仅在于读取文件和对对执行加法操作,因为ab的最大值为1e99。因此,您需要实现一个可以处理这么大的值(并对其进行加法运算)的结构。

提示:对字符串做些什么(天真的实现)。您也可以使用类似Boost.Multiprecision的名称。如果我没看错,Hackerearth支持C ++中的Boost库。

更多有关这些线程的信息:

What variable type for extremely big integer numbers?A good and basic implementation of BigInt class in C++BigInt class in C++Way to use big integer in C++BigInt for C++BIG INTEGER WITH C++

使用Boost.Multiprecision解决方案:

#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>

int main() {
    boost::multiprecision::cpp_int a, b;
    while (std::cin >> a >> b)
        std::cout << a + b << '\n';
}

答案 1 :(得分:1)

您可以从文件中逐个字符串读取它,将其转换为整数,然后求和。为了打破循环,可以使用!file.eof()表示循环,直到到达文件末尾。这是一个示例解决方案。 https://repl.it/@AhmadAnis/test

ifstream inFile("a1.txt");
    string ch;
    int x;
    int sum;
    while (!inFile.eof())
    {
        sum = 0;
        inFile >> ch;
        x = stoi(ch);
        sum +=x;
        inFile >> ch;
        x = stoi(ch);
        sum +=x;
        cout<<"Sum is "<<sum<<endl;
    }