I have made a txt file out of integers and chars that contains numbers and words.

When I read the file and get to a line that contains a number, I would like to put it into back into an integer.

How do i do this in c++?

thx

please post one or two lines of the file so we can see its format.

the data:

struct ALLE_PATIENTENDATA {
   int number;
   char name[20];
   int age;
   int operationtype;
};

putting data in the file:

ofstream bestand_patienten;
bestand_patienten.open ("patienten.txt", ios::trunc);
 
for (count = 1 ; count <= aantal_patienten; count++)
{
   bestand_patienten << patient[count].number << "\n";
   bestand_patienten << patient[count].name << "\n";
   bestand_patienten << patient[count].age << "\n";
   bestand_patienten << patient[count].operationtype << "\n";
}
 
bestand_patienten.close();

so the .txt goes:
1
Joe
45
2
2
Fred
50
1
...

trying to read it later:

ifstream bestand_patienten ("patienten.txt");
getline (bestand_patienten, data_uit_patientenbestand);

And now i have a string (for each line of the .txt file that i want to put in an integer -> at least the numerical data)

Don't you want to use atoi() to convert the string to an integer? Or just pop the entire string into a stream, which you can use to extract directly into the integer.

Okay, I'll look into that function.

thx

The C standard library offers several conversion functions.

  1. strtol - best error checking [ demo ]
  2. sscanf - some level of error checking [ demo ]
  3. atoi - poor level of error checking

But for C++, I'd recommend looking into stringstreams .

commented: Thanks for the info. +5
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.