如何从txt文件中读取数字行

How to read lines of numbers from txt file

本文关键字:读取 数字 文件 txt      更新时间:2023-10-16

所以在我的txt文件中,我有这样的数字

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

每次我都会有 3 个数字,我需要读取它们并将它们保存在一些变量中,任何人都可以帮助我如何做到这一点,因为大多数情况下我都在展示如何阅读字符的教程中,但如果我尝试将它们写在变量中,我会得到一些奇怪的数字......

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();

如果要读取数字,则需要.ignore()逗号(或将其提取到char中(。如果要保存元组,可以使用std::tuple<int, int, int>std::vector

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));
}

最简单的方法(我猜(是将逗号读入虚拟字符变量。

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

将逗号读入变量comma1comma2后,您可以忽略它们,因为您真正感兴趣的只是数字。

您的文件格式与 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
    }