首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将` string‘配置为从c++字符串读取?

如何将` string‘配置为从c++字符串读取?
EN

Stack Overflow用户
提问于 2020-11-10 16:37:36
回答 1查看 279关注 0票数 1

考虑一个cpp函数solve()。数字的字符串a (示例测试字符串)作为参数传递给函数solve()。我希望stdin读取字符串a中的数字。

这实际上是个压力测试。因此,在这个应力测试中,这个函数solve()被提供给return的一个字符串,这个结果将根据另一个函数solveFast()得到的另一个结果进行测试。

注意:-函数solve()中的算法已经给出了。我希望用我自己的算法(在solveFast()中)来测试这个算法.保证函数solve()中的算法对其测试输入提供正确的输出。

代码语言:javascript
运行
复制
#include <bits/stdc++.h>

using namespace std;

int solve(string s) {
    // below given: an algorithm that 
    //uses stdin to take input sample test case (i.e.,not string s)
    int n; //number of integers in string s

    //ignore the purpose of the code below. 
    //Just observe that it is taking the inputs as cin (not from string s.
    cin >> n;
    int first, second, large; 
    for (int i = 0; i < n - 1; i++) {
        if (i == 0) {
            cin >> first >> second;
            large = (second > first) ? second : first;
            if (second < first) first = second;
        } else {
            cin >> second;  // new num
            if (second > large) {
                first = large;
                large = second;
            }
            else if(second > first){
                first = second;
            }
        }
    }
    int result = large * first;

    return result;
}
int solveFast(string s) {
    
    /*
     * my solution here
     */

    return result;
}

int32_t main() {

    //stress-testing code starts here
    while (true) {
        
        string a;

        /*
         * generating a sample test case and storing it in a string 'a'
         */

        int res1 = solve(a);
        int res2 = solveFast(a);
        if(res1!=res2){
            cout << "Wrong answer: " << res1 << " " << res2 << endl;
            break;
        }
        else{
            cout << "OK\n";
        }
    }
    //stress-testig code ends

    /*
    for (int i = 1; i <= t; ++i) {
        int n;
        cin >> n;
        vector<int> numbers(n);
        for (int i = 0; i < n; i++) {
            cin >> numbers[i];
        }
        auto result = solve(numbers);
        cout << result << endl;
    }
    */

    return 0;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-10 17:03:29

将一个std::istream传递给您的函数,然后从一个字符串构造一个istream。作为一般规则,不要在代码中使用全局变量(如std::cin),这意味着要进行单元测试。

代码语言:javascript
运行
复制
#include <sstream>
#include <iostream>
int solve(std::istream& input, std::string s) {
     std::string variable;
     input >> variable;
     return 0;
}
void unit_test_solve() {
     std::istringstream input("some string");
     solve(input, "bla");
}
int real_code() {
     solve(std::cin, "bla");
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64772951

复制
相关文章

相似问题

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