簡體   English   中英

有沒有更好的方法來解決此問題-使用C ++的編程原理和實踐: 4-鑽?

[英]Is there a better way to solve this - Programming Principles & Practices Using C++: Ch. 4 - Drill?

我解決了這個問題-

編寫一個由while循環組成的程序(每次循環)讀取兩個int,然后打印它們。 當終止符“ |”時退出程序 輸入。

使用2種方法-

1)通過將輸入讀取為int並將第一個與'|'進行比較 像這樣 -

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

但是與此同時,我無法將124輸入為'|' == 124 '|' == 124

2)通過將輸入讀取為字符串 s並使用這樣的函數(我創建)將它們轉換為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;
}

但是現在這個問題進一步說要讀取雙精度數,而使用strtoint()方法意味着擴展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);

這並不是最好的,但確實可以(希望)!

當然,您始終可以使用<string>標頭中的std::stoi()std::stod()等函數。 實際上,我在以上方法中建議使用這些方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM