私のtxtファイルには、このような数字があります
1,200,400
2,123,321
3,450,450
4,500,250
毎回3つの数字があり、それらを読んでいくつかの変数に保存する必要があります。ほとんどの場合、文字の読み方を示すチュートリアルに参加しているので、誰でもこれを行う方法を手伝ってもらえますか?変数では、奇妙な数値が得られます...
私のtxtファイルには、このような数字があります
1,200,400
2,123,321
3,450,450
4,500,250
毎回3つの数字があり、それらを読んでいくつかの変数に保存する必要があります。ほとんどの場合、文字の読み方を示すチュートリアルに参加しているので、誰でもこれを行う方法を手伝ってもらえますか?変数では、奇妙な数値が得られます...
数字を読みたい場合は.ignore()
、カンマを (または に抽出してchar
) する必要があります。タプルを保存したい場合は、std::vector
ofを使用できますstd::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));
}
最も簡単な方法 (推測) は、カンマをダミーの char 変数に読み込むことです。
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
}
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();