Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

extracting numbers from a file 2

Status
Not open for further replies.

chineerat

Technical User
Oct 12, 2003
42
TT
Hi!! i dont know if you guys can help me

i have a file "numbers.txt" which have the format.

1,4,7,19,20
5,7,10,15,17
5,11,12,16,18
4,7,12,14,16
1,2,7,10,14
7,9,10,15,18
3,7,8,9,14
3,9,11,13,19
1,2,5,12,15

i want to get all the number and store them into a vector.


i've tried using a stream eg.

string cash_num ;

while (inputfile1>>cash_num){
// *CODE*
}

also i tried declaring cash_num as char as well as int
but nothing works. the commas are posing a problem.
is there anyother clever way to do this?

thanks in advance.
 
I'd try something like
Code:
int cash_num;
while (inputfile1>>cash_num){
  // do stuff
  char dummy;
  inputfile1 >> dummy; // burn a , or a newline
}

--
 
Code:
#pragma warning( disable: 4786 )	// identifier was truncated to '255' characters in the debug information.
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;


template <class T>
class AppendNumbersToVector
{
public:
	AppendNumbersToVector( vector<T>&  numVector )
	:	m_NumVector( numVector )
	{
		// Intentionally left blank.
	}

	void operator()( string  strNum )
	{
		stringstream numStream( strNum );
		T num;
		numStream >> num;
		m_NumVector.push_back( num );
	}

private:
	AppendNumbersToVector();	// Not permitted.
	AppendNumbersToVector<T>& operator=( const AppendNumbersToVector<T>& );	// Not permitted.

	// Member variables:
	vector<T>&		m_NumVector;
};


class PrintNums
{
public:
	template <class T>
	void operator()( T  num )
	{
		cout << num << endl;
	}
};


int main()
{
	ifstream inFile( "c:/temp/numbers.txt" );

	if ( inFile )
	{
		vector<string> vNumStrings;
		string strLine;
		string strNum;

		while ( getline( inFile, strLine ) )
		{
			stringstream numLine( strLine );

			while ( getline( numLine, strNum, ',' ) )
			{
				vNumStrings.push_back( strNum );
			}
		}

		vector<int> vNums;
		AppendNumbersToVector<int> appendNumsToVec( vNums );
		for_each( vNumStrings.begin(), vNumStrings.end(), appendNumsToVec );

		// Print out the vector of numbers.
		for_each( vNums.begin(), vNums.end(), PrintNums() );
	}
	else
	{
		cout << "Couldn't open file numbers.txt!" << endl;
	}

	return 0;
}
 
As in Salem's post but simpler(?;):
Code:
while (f >> x)
{
  v.push_back(x);
  f.ignore(1);
}
 
WOW cpjust das a lot i didn't try it but thanks anyway.
thanks Salem
but ArkM, you code worked PERFECT, i never heard of ignore.
thanks a MILLION though
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top