gpt4 book ai didi

c++ - 有没有更好的方法来解决这个问题 - Programming Principles & Practices Using C++ : Ch. 4 - Drill?

转载 作者:行者123 更新时间:2023-11-28 06:15:23 25 4
gpt4 key购买 nike

我解决了这个问题-

Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating '|' is entered.

使用 2 种方法 -

1) 通过将输入读取为 int 并将第一个输入与 '|' 像这样进行比较 -

int i1, i2;
while (cin >> i1){
if (i1 == '|')
break;
cin >> i2;
cout << endl << i1 << " " << i2 << endl;
}

但是有了这个,我不能输入 124 作为 '|' == 124

2) 通过将输入读取为 string 并使用函数(我创建的)将它们转换为 int -

// main function
string s1, s2;
int i1, i2;
while (cin >> s1){
if (s1 == "|"){
cout << "\nBreaking the loop\n";
break;
}
cin >> s2;
i1 = strtoint(s1);
i2 = strtoint(s2);
cout << endl << i1 << " " << i2 << endl;
}

// string to int
int strtoint(string s)
{
int i, j, val = 0, temp = 0;
for (i = s.size() - 1; i >= 0; --i){
temp = s[i] - '0';
for (j = 1; j < (s.size() - i); ++j)
temp *= 10;
val += temp;
}
return val;
}

但现在问题进一步说要读取 double ,使用第二种方法意味着扩展 strtoint() 以读取 double 值(这很烦人)。

我只想知道是否有更好的方法来解决这个问题,因为第一种方法有一个错误,而第二种方法需要更多代码。还是我应该只选择第二个?

最佳答案

使用第二种方法,但是这样实现转换更方便:

#include <sstream>

template <typename T>
T from_string (std::string const & s)
{
std::stringstream ss (s);
T ret;
ss >> ret;
return ret;
}

你可以这样调用它:

int a = from_string<int> (s1);
double d = from_string<double> (s2);

这不是最好的,但它确实有效(希望如此)!

当然,您始终可以使用 std::stoi() , std::stod()等来自 <string> 的功能 header 。事实上,我建议这些方法优于上述方法。

关于c++ - 有没有更好的方法来解决这个问题 - Programming Principles & Practices Using C++ : Ch. 4 - Drill?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30422712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com