2014-02-16 65 views
-3

SET2认可while循环不填充由于某种原因。 Set1工作得很好。字符串流不while循环

std::stringstream ss; 
std::string line; 
std::getline(infile, line); 
ss.str(line); 
int input; 

// Populate set1 
while(ss >> input) 
{ 
    set1.insert(input); 
    std::cout << "Populate set1 with " << input << "\t pos is " << set1.getUsed() << std::endl; 
} 

// Populate set2 
std::getline(infile, line); 
ss.str(line); 

std::cout << "\n2nd getline verification: " << line << std::endl; 

while (ss >> input) 
{ 
    set2.insert(input); 
    std::cout << "Populate set2 with " << input << "\t pos is " << set2.getUsed() << std::endl; 
} 

它只填充set1而不填充set2。感谢您的帮助。

编辑:现在读函数getline,谢谢。但它没有将“line”中的值输入到ss串流中,因此出于某种原因,set2的第二个循环无法识别。

+0

*不*你的程序做什么? infile定义在哪里?你有没有打开文件? – crockeea

+0

是的,它被定义。 set1导入就好了。 set2不。 –

+0

如果你已经解决了以前的问题,请更新代码以反映这一点,因为保留旧代码并引用一个没有任何证据的更正和正在运行的更新非常混乱。另外,什么是'set1'和'set2'?我知道他们是集合,但他们的目的是什么? – jrd1

回答

2

这并不令人惊讶,因为你只读行一次 - 你是不是在所有遍历流。您的代码应该是:

std::string line 
while(std::getline(infile, line)) { 
    std::cout << line << std::endl;//see what's in the line 
    //other code here... 
} 

为什么?因为你想保持从流中读取(直到遇到EOF)。换句话说:要继续阅读从流可以从流infile取得一行数据。

UPDATE:

的OP的问题是,相对于上述不同了。

例如,如果你的数据文件是这样的:

123 2978 09809 908098 
198 8796 89791 128797 

你可以阅读的数字是这样的:

std::string line 
while(std::getline(infile, line)) { 
    //you line is populated 
    istringstream iss(line); 
    int num; 

    while (!(iss >> num).fail()) { 
     //save the number 
    } 
    //at this point you've reached the end of one line. 
} 
+0

感谢您的回复,但它仍然只读取一行。 (输入); while(std :: getline(infile,line)) { while(iss >> input) { set1.insert(input); }} @ –

+0

HaakonSjøgren:正确的:因为这是你如何在你的代码做英寸如果我错了,请纠正我,但你最初的问题是你只能读一行。你现在有一个新的无关的问题 - 一个与你的代码的其他方面有关的问题,你没有在你的原始文章中提到。请编辑您的帖子以反映这一点。 – jrd1

+0

@HaakonSjøgren:编辑。 – jrd1