簡體   English   中英

在 C++ 中使用 istringstream 將字符串拆分為整數

[英]Splitting a string into integers using istringstream in C++

我正在嘗試使用istringstream將一個簡單的字符串拆分為一系列整數:

#include <string>
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

int main(){

    string s = "1 2 3"; 
    istringstream iss(s);   

    while (iss)
    {
        int n;
        iss >> n;
        cout << "* " << n << endl;
    } 
}

我得到:

* 1
* 2
* 3
* 3

為什么最后一個元素總是出現兩次? 如何解決?

它出現兩次,因為你的循環是錯誤的,正如(間接)在http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5while (iss)while (iss.eof())在這種情況下)。

具體來說,在第三次循環迭代中, iss >> n成功並獲得3 ,並使流保持良好狀態。 由於這種良好狀態,循環然后第四次運行,直到下一個(第四個) iss >> n隨后失敗,循環條件才被破壞。 但是在第四次迭代結束之前,您仍然輸出n ... 第四次。

嘗試:

#include <string>
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
    string s = "1 2 3"; 
    istringstream iss(s);   
    int n;

    while (iss >> n) {
        cout << "* " << n << endl;
    } 
}

希望這可以幫助:
是 : 1 2 3
迭代 1
iss : 1 2 3 (最初)
n=1
是 : 2 3
//* 1 被打印
迭代 2:
iss : 2 3 (最初)
n=2
是 : 3
//* 2 被打印
迭代 3
是 : 3
n=3
伊斯:''
迭代 4
伊斯:''
n 未更改//為 iss 的eof設置了標志,因為沒有來自流的進一步輸入
伊斯:''

正如上面的帖子正確提到的,while (iss) 與 while (iss.eof()) 沒有什么不同。
在內部,函數(istream::operator>>) 通過首先構造一個哨兵對象來訪問輸入序列(將 noskipws 設置為 false [這意味着空格是分隔符,您的列表將是 1,2,3])。 然后(如果良好[此處未達到 eof]),它調用num_get::get [Get the next integer] 來執行提取和解析操作,相應地調整流的內部狀態標志。 最后,它在返回之前銷毀哨兵對象。

參考: http : //www.cplusplus.com/reference/istream/istream/operator%3E%3E/

暫無
暫無

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

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