2013-10-05 41 views
-3

读取数字线所以在我的txt文件我有这个如何从txt文件

1,200,400 
2,123,321 
3,450,450 
4,500,250 

每一次我都会有3个数字相同的数字,我需要阅读它们,并将它们保存在一些变量,谁能帮助我如何做到这一点,因为主要是我得到的教程展示了如何读取字符,但如果我试图把它们写在变量中,我得到一些奇怪的数字...

回答

0
std::fstream myfile("filename.txt", std::ios_base::in); 

int a ,b,c; 
char ch; //For skipping commas 
while (myfile>> a >> ch >> b>> ch >>c) 
{ 
    // Play with a,b,c 
} 

myfile.close(); 
+0

什么输入逗号? – john

+0

因为简单,我真的很喜欢这个,但我怎样才能让它读取直到文件的结尾,就像所有的行不只是一个。 – Kebapmanager

+0

@ user2850409只要流处于良好状态,while循环将读取文件,即直到文件结尾 – P0W

0

如果你想阅读数字,你需要.ignore()这个逗号(或者把它解压到一个char)。如果你想保存的元组,你可以使用std::vectorstd::tuple<int, int, int>的:

std::vector<std::tuple<int,int,int>> myNumbers; 
int number1, number2, number3; 

while(((file >> number1).ignore() >> number2).ignore() >> number3){ 
    myNumbers.push_back(make_tuple(number1, number2, number3)); 
} 
0

最简单的方法(我猜)是读取逗号进入虚拟焦炭变量。

int num1, num2, num3; 
char comma1, comma2; 
while (file >> num1 >> comma1 >> num2 >> comma2 >> num3) 
{ 
    ... 
} 

读了逗号入变量comma1comma2那么你可以忽略它们,因为所有你真正感兴趣的是数字。

+0

我真的很喜欢这个,但它只读取1行,我怎么能让它读取更多然后1行? – Kebapmanager

+0

@ user2850409它应该读取多行,这就是我使用while循环的原因。也许你应该问一个新问题,如果你有麻烦。 – john

0

您的文件格式与CSV文件格式相同,因此您可以使用它。

http://www.cplusplus.com/forum/general/13087/

ifstream file ("file.csv"); 
    string value; 
    while (file.good()) 
    { 
     getline (file, value, ','); // read a string until next comma: http://www.cplusplus.com/reference/string/getline/ 
     cout << string(value, 1, value.length()-2); // display value removing the first and the last character from it 
    } 
+0

cplusplus.com是一个糟糕的习惯和编码风格的来源。这是一个例子。 – Manu343726

+0

但我不需要显示我的价值,我需要在我的代码中使用它来构建我的关卡,这使得第一个和最后一个字符成为问题。 – Kebapmanager