2012-04-05 121 views
1

我想存储一些整数在一个文件中,我用','作为分隔符存储它。现在,当我读取文件时,我使用getline()读取该行并使用tokenizer分隔文件。但是,我无法终止该行,因此我需要在getline中终止一些布尔条件。如何终止使用getline()

while(getline(read,line)) { 
     std::cout<<line<<std::endl; 
     std::istringstream tokenizer(line); 
     std::string token; 
     int value; 

     while(????CONDN???) { 
       getline(tokenizer,token,','); 
       std::istringstream int_value(token); 
       int_value>>value; 
       std::cout<<value<<std::endl; 
     } 
    } 

请指教。

回答

2

在你的情况是足够用了getline以同样的方式,你在外环做:

while(getline(tokenizer, token, ',')) 

虽然最有可能我会做这样的事情:

while(std::getline(read,line)) { // read line by line 
    std::replace(line.begin(), line.end(), ',', ' '); // get rid of commas 
    std::istringstream tokenizer(line); 
    int number; 

    while(tokenizer >> number) // read the ints 
     std::cout<<number<<std::endl; 
} 

还有其他两个选择 - 使用Boost。

String Algorithms

#include <boost/algorithm/string.hpp> 
... 
std::vector<std::string> strings; 
boost::split(strings, "1,3,4,5,6,2", boost::is_any_of(",")); 

tokenizer

#include <boost/tokenizer.hpp> 
typedef boost::char_separator<char> separator_t; 
typedef boost::tokenizer<separator_t> tokenizer_t; 
... 
tokenizer_t tokens(line, sep); 
for(tokenizer_t::iterator it = tokens.begin(); it != tokens.end(); ++it) 
    std::cout << *it << std::endl; 

如果预期会遇到非int,非分离的字符,例如1 3 2 XXXX 4。那么你必须决定在这种情况下做什么。 tokenizer >> number将停止在不是intistringstream错误标志将被设置。 boost::lexical_cast也是你的朋友:

#include <boost/lexical_cast.hpp> 
... 
try 
{ 
    int x = boost::lexical_cast<int>("1a23"); 
} 
catch(const boost::bad_lexical_cast &) 
{ 
    std::cout << "Error: input string was not valid" << std::endl; 
} 

最后,在C++ 11你有stoi/stol/stoll功能:

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string test = "1234"; 
    std::cout << std::stoi(str) << std::endl; 
} 
+0

此代码打印一个号码...... – howtechstuffworks 2012-04-05 09:32:17

+0

@howtechstuffworks:固定式,对不起。 – Anonymous 2012-04-05 09:40:28