2013-05-02 76 views
0

所以,我有如下代碼:變量不更新從istringstream

#include <iostream> 
#include <string> 
#include <sstream> 
#include <fstream> 
#include <cctype> 

using namespace std; 

int main(int argc, char *argv[]) 
{ 
    char c; 
    ifstream f("test.txt"); 
    char n; 
    char z; 
    char o; 
    int output; 
    istringstream in; 
    string line; 
    while (getline(f, line)) 
    { 
     in.str(line); 
     do 
     { 
      c = in.get(); 
     } 
     while (isspace(c)); 
     in.unget(); 
     in >> n >> c >> z >> c >> o >> c >> output; 
     cout << n << z << o << output << endl; 
    in.str(string()); 
    } 
    f.close(); 
    return 0; 
} 

和文件test.txt包含:

A,B,C,1 
B,D,F,1 
C,F,E,0 
D,B,G,1 
E,F,C,0 
F,E,D,0 
G,F,G,0 

每行的文本文件格式是「char,char,char,bool」(我忽略了現在可能有空白的事實)。

當我編譯並運行該代碼((使用Visual Studio 2010),我得到:

ABC1 
ABC1 
ABC1 
ABC1 
ABC1 
ABC1 
ABC1 

很顯然,這不是我想要的東西沒有人有答案,這是怎麼回事的。 ?

回答

1

速戰速決,把istringstream內循環復位輸入指示燈:

//istringstream in; ----------+ 
string line;     | 
while (getline(f, line))  | 
{        | 
    istringstream in; <--------+ 

    in.str(line); 
    do 
    { 
     c = in.get(); 
    } 
    while (isspace(c)); 
    in.unget(); 
    in >> n >> c >> z >> c >> o >> c >> output; 
    cout << n << z << o << output << endl; 
    //in.str(string()); <-------------------- you can remove this line 
} 
f.close(); 

如果不復位輸入指標,in.get將不按照你的預期工作。或者您可以簡單地使用seekg(0)

+0

添加istringstream內循環的伎倆。使用in.seekg(0);沒有。 – 2013-05-02 20:09:42

+0

爲什麼不簡單地調用'clear()'而不是'str(std :: string())'? – 2013-05-02 21:52:01

+0

@vlad由於清除重置錯誤標誌,而不是stringstream的內容。 – 2013-05-02 22:46:12

0

當您更改字符串流的內容時,默認情況下它會將位置指針設置爲流的末尾:http://www.cplusplus.com/reference/sstream/stringstream/str/in.str(line);後添加in.seekg(0);,它應該工作:

#include <iostream> 
#include <string> 
#include <sstream> 
#include <fstream> 
#include <cctype> 

using namespace std; 

int main(int argc, char *argv[]) 
{ 
    char c; 
    ifstream f("test.txt"); 
    char n; 
    char z; 
    char o; 
    int output; 
    istringstream in; 
    string line; 
    while (getline(f, line)) 
    { 
     in.str(line); 
     in.seekg(0); 
     do 
     { 
      c = in.get(); 
     } 
     while (isspace(c)); 
     in.unget(); 
     in >> n >> c >> z >> c >> o >> c >> output; 
     cout << n << z << o << output << endl; 
    in.str(string()); 
    } 
    f.close(); 
    return 0; 
} 
+0

其實這並沒有工作。我仍然得到相同的輸出。 – 2013-05-02 20:06:37

+0

@HadenPike我編輯它以包含完整的代碼。它適用於我的電腦 - 可能是某種編譯器的區別? – nullptr 2013-05-02 20:09:14

+0

Visual C++ 2010。 – 2013-05-02 22:50:11