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

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.

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 .

Comments
Thanks for the info.
This article has been dead for over six months. Start a new discussion instead.