簡體   English   中英

如何在C ++的循環中在StringStream中插入新字符並提取到字符串?

[英]How to insert a new character in a StringStream and extract to string within a loop in C++?

我不確定我的代碼出了什么問題。 我希望在for循環的每次迭代中將字符更新並插入到stringstream中,並提取到一個字符串,以便以后用於附加到char []變量上。 我希望收到的變量內容輸出為:CPU代表什么? A.中央處理單元B.控制編程單元C.中央編程單元D.控制處理單元取而代之的是我得到所有A。 如何更新流中的值,以使溫度取值“ A。”,“ B。”,“ C。”和“ D.”。 我對C ++並不陌生,但是對使用stringstream不熟悉。 誰能解釋正在發生的事情以及我如何能夠解決它? 我在Unix環境中使用g ++編譯器。

    char content[1096];
    int numOfChoices;
    char letterChoice = 'A';
    string choice, temp;
    stringstream ss;

    strcpy ( content, "What does CPU stand for?");
    cout << "How many multiple choice options are there? ";
    cin >> numOfChoices;
    cin.ignore(8, '\n'); 
    for (int i = numOfChoices; i > 0; i--)
    {
       strcat (content, "\n");
       ss << letterChoice << ".";
       ss >> temp;
       strcat(content, temp.c_str());
       ss.str("");
       cout << "Enter answer for multiple choice option " 
            << letterChoice++ <<":\n--> ";
       getline (cin, choice);
       strcat(content, " ");
       strcat(content, choice.c_str());
     }
       cout << content << endl;

在執行插入和提取時,應始終檢查是否成功:

if (!(ss << letterChoice << "."))
{
    cout << "Insertion failed!" << endl;
}

這樣,您可以立即知道出了點問題。 在第一個循環中,當您執行ss >> temp; 它提取流中的所有字符並將它們置於temp 但是,已到達文件末尾,因此設置了eofbit。 因此,在下一個循環中,當您執行ss << letterChoice << "."; ,則操作失敗,因為設置了eofbit。 如果添加ss.clear(); ss >> temp; 該代碼將起作用,因為您在設置了eofbit之后重置了流狀態。

但是,您不需要在代碼中使用stringstream或所有那些舊的C函數。 您可以使用std::string進行所有操作,如下所示:

string content = "";
int numOfChoices;
char letterChoice = 'A';
string choice;

content += "What does CPU stand for?";
cout << "How many multiple choice options are there? ";
cin >> numOfChoices;
cin.ignore(8, '\n'); 
for (int i = numOfChoices; i > 0; i--)
{
   content += "\n";
   content += letterChoice;
   content += ".";
   cout << "Enter answer for multiple choice option " 
        << letterChoice++ <<":\n--> ";
   getline (cin, choice);
   content += " ";
   content += choice;
 }
 cout << content << endl;

暫無
暫無

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

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