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

		tmp = new myStruct;
		tmp -> name = name_in;
		tmp ->link=head;

here is the struct definition

struct myStruct
	string name;

	int number;

	myStruct* link;

typedef myStruct* nodePtr;
10 Years
Discussion Span
Last Post by joshmo

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

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


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:

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.