1

I am a newer to C++, Now what I am going to do is creating a file, and write int values into it Then I want to get those int values with get function!(Here the excepted type of return is int ) Actually this is an index file, so what I am going to put into it are all int values! But I found that both fstream.put and fstream.get could only operate char values. So is there anyone would like to help me, how to do my job. And here is my code

vector<int> tra1;
vector<int> tra2;
int last_capa = 0;
    for(int i=1;i<97;i++){
        output.put(tra1[i-1] * 5 + tra2[i-1] + last_capa);
        last_capa += (tra1[i-1] - 1) * 5 + tra2[i - 1];
    } 

Below is the code to read int Here I try to get an int number to operate

vector<int> tra4
output.seekg(100);
unsigned int n = output.get() + tra4[2];

Thanks for your help

Haoran

xiawi
  • 1,772
  • 4
  • 19
  • 21
Haoran
  • 11
  • 1
  • 1
  • 2
  • 1
    http://stackoverflow.com/questions/4672991/proper-casting-for-fstream-read-and-write-member-functions You have to cast what you're reading from `char*` to the type you want to read. – dau_sama Apr 25 '16 at 03:23
  • Your file does not contain "int values". It contains text that looks like numbers to a human (when rendered per ASCII). – Lightness Races in Orbit Apr 27 '16 at 13:40

3 Answers3

1

Alternatively instead of get, you can use the fstream's operator >> to read the value from the file into an int.

fstream fs("input.txt", std::fstream::in); //input file
int k;
while(fs >> k)
{
   //do something with k
}
fs.close();
1337ninja
  • 136
  • 2
  • 10
1

An alternative to the fstream operator >> is to use read/write. To write an int value:

std::ofstream f_out("my_file.txt", std::ofstream::binary);
int n;
f_out.write((char *) & ( n ), sizeof(n));

An to read:

std::ifstream("my_file.txt", std::ifstream::binary);
int n;
f_in.read((char *)&n, sizeof(n));

To read the 100th int:

std::ifstream("my_file.txt", std::ifstream::binary);
f_in.seekg(100*sizeof(int), std::ios::beg);
int n;
f_in.read((char *)&n, sizeof(n));
xiawi
  • 1,772
  • 4
  • 19
  • 21
0

You could try the oldish C method sprintf to put some int in a string, and then put the string in your file like so :

sprintf(theNameOfYourString,"%d",n);

EDIT : Of course then you have to put the string theNameOfYourString in your file, sprintf only allows you to place things in a String.

Thomas
  • 337
  • 2
  • 8
  • Usually in `C++` one would overload `operator<<` to achieve the same result. – dau_sama Apr 25 '16 at 03:24
  • Thanks for your help Roncoli. But if I do it in your method how can I get the int value back? – Haoran Apr 25 '16 at 03:34
  • I'm not sure, but I suppose the get() function returns a String. You can do operations on this String, such as atoi(), that converts a String to an int. EDIT : Here is a link : http://www.cplusplus.com/reference/cstdlib/atoi/ – Thomas Apr 25 '16 at 03:43