簡體   English   中英

如何使用stringstream對象將整數多次轉換為字符串?

[英]How to convert an integer to string multiple times using stringstream object?

我想將輸入作為整數,然后將其與字符串連接。 這將是多次。 輸出將是具有此新整數值的前一個字符串。 輸入整數后,我使用stringstream對象對其進行了轉換。 然后,我將其連接起來。 但是我第一次獲得了預期的輸出。 但是,下一次我從用戶那里獲取輸入並嘗試將其與連接部分中的上一個字符串輸出字符串連接時,與我的第一個輸入整數相同。 因此,如何使用此stringstream對象進一步使用。

這是我的代碼:

string s = "Previous Choices :   ";
    int n;
    string d;
    stringstream ss;
    while(1) {
        cin>>n;
        ss << n;
        ss >> d;
        s += d;
        cout<<s<<”   ”<<endl;
}

我的輸入

10
20
30

我的預期輸出是

Previous Choices :   10
Previous Choices :   10 20
Previous Choices :   10 20 30

但是輸出是這樣的:

Previous Choices :   10
Previous Choices :   10 10
Previous Choices :   10 10 10

您沒有清除stringstream對象以供進一步使用。 這就是為什么它包含第一個輸入值並將其添加到所有輸入中的原因。

因此,要清除該對象,您只需添加以下代碼

ss.clear();

然后您的代碼將像這樣

string s = "Previous Choices :   ";
    int n;
    string d;
    stringstream ss;
    while(1) {
        cin>>n;
        ss << n;
        ss >> d;
        s += d;
        cout<<s<<”   ”<<endl;
        ss.clear();
}

我做了這樣的事情:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
string s = "Previous Choices : ";
    int n;
    stringstream ss;
    while(1) 
    {
        cin >> n;
        ss << n;
        //cout << "in ss stream is: " << ss.str() << endl;
        s = s + ss.str() + " ";
        cout << s << endl;
        ss.str(string());
    }
    return 0;
}

它按您預期的那樣工作。

您可以更簡單地完成此操作,而無需中間sd ,而直接使用流作為累加器。

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    stringstream ss;
    ss << "Previous Choices : ";
    while(1) 
    {
        int n;
        cin >> n;
        ss << n;
        cout << ss.str() << endl;
    }
    return 0;
}

暫無
暫無

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

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