0

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

4
Contributors
5
Replies
6
Views
10 Years
Discussion Span
Last Post by Dave Sinkula
Featured Replies
  • The C standard library offers several conversion functions. [list=1][*][INLINECODE]strtol[/INLINECODE] - best error checking [[URL=http://www.daniweb.com/code/snippet441.html]demo[/URL]] [*][INLINECODE]sscanf[/INLINECODE] - some level of error checking [[URL=http://www.daniweb.com/code/snippet266.html]demo[/URL]] [*][INLINECODE]atoi[/INLINECODE] - poor level of error checking[/list]But for C++, I'd recommend looking into [URL="http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2"]stringstreams[/URL]. Read More

0

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)

0

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.

1

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 .

Votes + Comments
Thanks for the info.
This topic has been dead for over six months. 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.