如何从txt文件中读取数字行
How to read lines of numbers from txt file
所以在我的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)
{
...
}
将逗号读入变量comma1
并comma2
后,您可以忽略它们,因为您真正感兴趣的只是数字。
您的文件格式与 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
}
相关文章:
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 如何从文件中读取数字并在数组中使用它们?
- 使用模板化函数从CSV文件中读取数字
- 根据数字在 c++ 中作为矩阵的位置从文件中读取数字
- 如何从文件中读取数字序列?
- 如何允许我的程序成功读取数字包含的文件
- 如何仅从C 中的文本文件中读取数字
- 从没有分隔符 C++ 的文件读取数字出现次数
- 读取数字并转换为单词
- 从文件,特定行中仅读取数字
- 从TextFile中读取数字,并检查它们是否在范围内
- C 从文本文件中读取数字,忽略注释
- 从文件读取数字列表到动态数组
- 我正在尝试从文件中读取数字
- 从txt文件中读取数字,添加一些数字,然后在c ++中将其重写为其他文件
- C++如何从文件中读取数字并将其分配到数组中的相应位置
- 读取数字的文本文件,并存储在C++的整数数组中
- 从文件中读取数字
- 从文本中读取数字并输出平均值