Am trying to extract a string of characters and numbers from a text file into two different data types in a linked list...i.e the if the text file has the data

myname 100

i want the "myname" to be stored as a string and then the 100 as an integer..can anyone help with an idea of how to do it?? so far i can only the whole string..thanx

for(i=0;i<3;i++)
	{
		getline(infile,name_in);
		tmp = new myStruct;
		tmp -> name = name_in;
		tmp ->link=head;
		head=tmp;
	}

here is the struct definition

struct myStruct
{
	string name;

	int number;

	myStruct* link;
};

typedef myStruct* nodePtr;

Recommended Answers

All 4 Replies

First of all, I would suggest you read your file like this:

string line;
ifstream infile("abcdef.txt");
while (getline(infile, line))
{ // do stuff
}

That way you can use the benefits of the std::string and you don't have to worry about the siz of char arrays etc.

So now you have one line out of the file.
Now to convert the number to an int:

int some_int;
string number;
string line = "blabla 100";

number = line.substr(line.find(' ')+1,3);

istringstream buffer(number);
		
buffer >> some_int;
cout << some_int + 55 << endl; //to show it's int

Note that this code assumes that the input was read successfully and has only 1 space in it. The number can't be more then 3 digits. But those are problems you can solve yourself ;)

[edit]
And don't forget to #include <sstream>

alrite thanx... am gona try that out...could you please explain to me line 5 and line 7..thanx

5:
substr() substracts a number of characters from a string. Parameter 1 is the startposition for extraction, parameter 2 is the number of chars to be extracted.
So for param 1 I say "find(' ')" which will return the position of the first space in the string. The char next to the space is the first char we want to extract (the '1' from '100'). So that's what the +1 does.
So in short: "extract 3 chars from 'line' starting from the char next to the first space"
I hope I'm being clear enough..

line 7:
istringstream

yea..thats clear..thanx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.