so my program has to read data from text file and pass it to the function. text file contains integer and string in every line. it looks like this:

23456 john
96512 martin
56985 wendy

i've written it in C using this code:

while (fscanf(filestream, "%d%s", &key, &value) == 2){
    Insert(key, value);
}

it would be very helpful if someone could write the exact equivalent in C++ for the given code.

Thank you in advance.

Recommended Answers

All 4 Replies

Don't think anyone will write the code for you, too bad I don't really know C to begin with.

I bet you can find very similiar threads in the C++ forum history. If not, you should check getline, << and maybe string2int

Here is an algorithm for it :

//open a file using fstream objects say file and functions like file.open() in input mode
// Create a string variable which can act as a buffer for holding the values
while(getline( <file descriptor value>, <buffer object>)!=NULL)
{
int key;
string skey,value;
//extract string value of key into skey and convert it into integer using istringstream
//extract string value of key into value
//With the help of a new fstream object write into the file you want it to.
//erase the buffer for providing space for next input using file.erase() function
}

so i've got a bit further. i would've never believed that something like this can work, but it passes the right values. the problem is that it reads only the first line. here's the updated code:

file >> key;
file >> value;
d->insert(key, value);

how can i read the lines following the first one???

Well use getline function. It advances the file get pointer to next line automatically.Or even you can look upon f.seekg() function.

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.