2012-10-29 72 views
-2

我试图从.txt文件中读取一些数字,以空格隔开。 (一行上最多4个数字)。从字符串中的getline中读取文件,然后从int数组中分割字符串中的数字

  • 我得到的线,但我怎样才能将其转换为int数组,那么 后,我移动到第二线覆盖阵列?

例: .txt文件

2 5 8 14 11 
50 40 30 20 10 
18 17 16 15 14 

代码:

fstream f("C:\\n.txt"); 
string wtf; 
int n; 
while(f>>n) 
{ 
getline(f,wtf); 
//transform the wtf string into int array? 
//do what ever... 
//clear the array? 
} 
+0

你知道的家伙,你可以downvote,并告诉这个可怜的家伙他的问题有什么问题。 – Iznogood

回答

0

使用std::istringstreamstd::vector

std::string line; 
while(std::getline(f, line)) { 
    std::istringstream iss(line); 
    std::vector<int> v; 
    int i; 
    while(iss > i) { 
    v.push_back(i); 
    } 
    // do whatever 
    // vector cleared automatically 
} 
+0

有没有矢量和推回功能的方法?谢谢 – Alex

+0

是的,你可以使用'std :: list <>',或'std :: array <>'(如果你知道编译时间的大小),或者甚至是一个裸数组(尽管我不会推荐。) –

相关问题