How cast char to int in C++? (File Handling) - c++

Lets say I have a txt file list.txt
The txt file has list of integers ,
88
894
79
35
Now I am able to open the file and display the contents in it but not able to store it in an integer array.
int main()
{
ifstream fin;
fin.open("list.txt");
char ch;
int a[4],i=0;
while((!fin.eof())&&(i<4))
{
fin.get(ch);
a[i]=(int)ch;
cout<<a[i]<<"\n";
i++;
}
fin.close();
return 0;
}
Please help!!

You can use >> to read text-formatted values:
fin >> a[i]
You should check for the end of the file after trying to read, since that flag isn't set until a read fails. For example:
while (i < 4 && fin >> a[i]) {
++i;
}
Note that the bound needs to be the size of the array; yours is one larger, so you might overrun the array if there are too many values in the file.

Try the following
#include <iostream>
#include <fstream>
int main()
{
const size_t N = 4;
int a[N];
std::ifstream fin( "list.txt" );
size_t i = 0;
while ( i < N && fin >> a[i] ) i++;
while ( i != 0 ) std::cout << a[--i] << std::endl;
return 0;
}

Related

Reads a file containing 10 data items that populate the array create in struct and Displays the contents of the array after it has been populated

enter image description here
the original question attached. I am stuck populating the file into the array and then displaying it. the file only has 10 numbers. this is in c++
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, const char * argv[]) {
const int SIZE = 10;
struct stemp{
int stud_id_num;
int num_credit_completed;
double cum_gpa;
}stemp[SIZE];
ifstream inputFile;
inputFile.open("stemp.txt");
int count = 0;
while(!inputFile.eof()){
inputFile >> stemp[SIZE];
}
inputFile.close();
return 0;
}
Several mistakes here
First while(!inputFile.eof()) { is not the correct way to read until the end of file. It should be while (inputFile >> ...) {
Second inputFile >> stemp[SIZE]; reads into stemp[10] but your array is only size 10, so stemp[10] doesn't exist. What you probably meant was
inputFile >> stemp[count];
count++;
That way each read goes into a different element of the array, depending on the value of the count variable.
Putting that together you have
int count = 0;
while (inputFile >> stemp[count]) {
count++;
}
That loop is now correct, but I'm afraid your biggest mistake is yet to come. You see inputFile >> stemp[count] isn't going to work. C++ doesn't magically know how to read your file into your structure. You have to write the code to do that. You have to write a version of >> that works with your file and your structure.
In other words you have to write this
istream& operator>>(istream& in, stemp& s)
{
// code to read s from in goes here
}
What about this solution:
stemp.txt
1 2 2.1
3 4 3.2
5 6 5.3
7 8 7.4
9 10 11.5
11 12 13.6
13 14 17.7
15 16 19.8
17 18 23.9
19 20 27.10
main.cpp
#include <fstream>
#include <iostream>
using namespace std;
constexpr size_t SIZE = 10;
struct stemp
{
int id;
int credits;
double cum_gpa;
};
void printStemp(stemp const& s, int const& index)
{
printf(
"Stemp %d\nid: %d\ncredits: %d\ncum_gpa: %.2f\n\n",
index, s.id, s.credits, s.cum_gpa
);
}
int main()
{
stemp arr[SIZE];
ifstream inputFile;
inputFile.open("stemp.txt");
if (inputFile.fail())
return 0;
for (size_t i = 0; i < SIZE; i++)
inputFile >> arr[i].id >> arr[i].credits >> arr[i].cum_gpa;
inputFile.close();
cout << "Displaying content:\n\n";
for (size_t i = 0; i < SIZE; i++)
printStemp(arr[i], i);
return 0;
}

How can I load a bunch of array elements from a text file?

How could I load array from a text file in C++.
I can't get all array elements from the file.
and here is my code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream file("file.txt");
if(file.is_open())
string myArray[5];
}
When reading from a file, the advice is to use a dynamic container, such as std::vector:
std::vector<int> database;
int number;
ifstream data_file("file.txt");
while (data_file >> number)
{
database.push_back(number);
}
The above fragment will read integers from the file, regardless of the quantity.
Arrays
The issue with arrays is that you need to know the quantity before you declare the array.
const size_t capacity = 16;
int array[capacity];
for (unsigned int i = 0; i < capacity; ++i)
{
data_file >> array[i];
};
The above fragment assumes that there is at least 16 numbers in the file.
you will make counter to continute counting the data until you stop reading from the file then open an array it's size = this counter , then open new counter say to put the fisrt number in the first index in the array and here is the code
int i=0 , j=0 ;
ifstream file("statfile.txt") ;
while(file >> data) {i++ ;}
double arr[i];
file.close();
ifstream newfile("statfile.txt");
while(newfile >> arr[j]) {j++ ;}
for(j=0 ; j<i ; j++) {cout << arr[j] << " " ;}

Can't get last int from .txt file

My Issue involves reading integers from a text file, saving them to an array and then copying the array to a new .txt file.
So there is a file "krol.txt"
2 4
3 7
3 13
2 4
3 1
The problem is that it never ever save the last '1' from the input .txt file. I have no idea why. I think its about EOF on last character in file but why it works like that? Can anyone help me?
This is my code:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
ofstream outFile;
ifstream fin;
fin.open("krol.txt");
int l=0;
char ch;
while (fin.good()) {
fin.get(ch);
if(ch=='\n') l++;
}
fin.close();
fin.open("krol.txt");
int temp[l][2];
int savel=l;
l=0;
int i=0;
while (fin >> (temp[l][i])) {
i++;
if(i==2) {
i=0;
l++;
}
}
outFile.open("save.txt");
for (int i=0, j=0;j<savel;i++) {
if (i==2) {
i=0; j++;
}
outFile << temp[j][i];
}
outFile.close();
system("PAUSE");
return 0;
}
This saves all the numbers just fine. The problem is, it stores additional numbers in save.txt.
With
while (fin.good()){
...
}
you count the last line twice. This gives you two additional uninitialized ints. These two ints can show up as any integer.
I see two problems. Your first loop to get the number of lines should be more like
while (fin.get(ch)){
if (ch == '\n')
l++;
}
If the last line doesn't have a final \n, you could end with one line less than you need.
And the output loop could be simplified to
for (int j = 0; j < savel; j++){
for (int i = 0; i < 2; i++)
outFile << temp[j][i] << ' ';
}
And finally, if you use c++, you should consider using std::vector instead of plain arrays. Then you don't need to preallocate your array and can read the file in just one pass.
There might be 4 '\n' chars in that file have you considered that?

how to write content of an array to hard disk

i am trying to write content of a very large char array to the hard disk.
I have the following array(actually the size of it is going to be very large)
I am using the array as a bit array and after inserting a specified number of bits into it I have to copy its content to another array and write this copy into hard disk. I then empty the content of the array by assigning it 0 for further use.
unsigned char bit_table_[ROWS][COLUMNS];
Use ofstream, copy and ostream_iterator to leverage the power of STL:
#include <algorithm>
#include <fstream>
#include <iterator>
#include <iostream>
#include <vector>
using namespace std;
int main() {
unsigned char bit_table_[20][40];
for (int i = 0 ; i != 20 ; i++)
for (int j = 0 ; j != 40 ; j++)
bit_table_[i][j] = i^j;
ofstream f("c:/temp/bit_table.bin", ios::binary | ios::out);
unsigned char *buf = &bit_table_[0][0];
copy(buf, buf+sizeof(bit_table_), ostream_iterator<unsigned char>(f, ""));
return 0;
}
You should open a file for writing, and then write the array to it:
FILE * f;
f = fopen(filepath, "wb"); // wb -write binary
if (f != NULL)
{
fwrite(my_arr, sizeof(my_arr), 1, f);
fclose(f);
}
else
{
//failed to create the file
}
References: fopen, fwrite, fclose
Use a file or a database...
a file is simple to create :
FILE * f;
int i,j;
f = fopen("bit_Table_File", "w");
for (i = 0 , i< ROWS , i++)
{
for (j = 0 , j < COLUMNS , j++)
{
fprintf(f, "%2x", bit_table_[i][j]);
}
}
to read the contents of the file, you can use fscanf starting from the beginning of the file :
FILE* f = fopen("myFile","r");
for (i = 0 , i< ROWS , i++)
{
for (j = 0 , j < COLUMNS , j++)
{
fscanf(f, "%2x", &(bit_table_[i][j]));
}
}
whereas you have to install a database (and number of tables needed) and use specific instructions to write to it.
You can Store the value of array in file
so you need
include the fstream header file and using std::ostream;
declare a variable of type ofstream
open the file
check for an open file error
use the file
close the file when access is no longer needed
#include <fstream>
using std::ofstream;
#include <cstdlib>
int main()
{
ofstream outdata;
int i; // loop index
int array[5] = {4, 3, 6, 7, 12};
outdata.open("example.dat"); // opens the file
if( !outdata ) { // file couldn't be opened
cerr << "Error: file could not be opened" << endl;
exit(1);
}
for (i=0; i<5; ++i)
outdata << array[i] << endl;
outdata.close();
return 0;
}

How to read n integers from standard input in C++?

I need to read something like:
5 60 35 42
2 38 6
5 8
300 1500 900
And then save the first line in an array. After calling other functions do the same with the next line, and so on.
I try with gets() and then use sscanf() to scan the integers from the string, but I don't know how to read n numbers from a string.
C++
If you have an unknown number of entries spread across an unknown number of lines, ending at EOF:
int n;
while(cin >> n)
vector_of_int.push_back(n);
If you have a known number of entries spread across an unknown number of lines:
int n;
int number_of_entries = 20; // 20 for example, I don't know how many you have.
for(int i ; i < number_of_entries; ++i)
if(cin >> n)
vector_of_int.push_back(n);
If you have an uknown number of entries on a single line:
std::string str;
std::getline(std::cin, str);
std::istringstream sstr(str);
int n;
while(sstr >> n)
vector_of_int.push_back(n);
If you have a unknown number of entries spread across a known number of lines:
for(int i = 0; i < number_of_lines; ++i) {
std::string str;
if(std::getline(std::cin, str)) {
std::istringstream sstr(str);
int n;
while(sstr >> n)
vector_of_int.push_back(n);
}
}
I've seen input files like this for competitions before. If speed is more of an issue than error detection, you could use a custom routine. Here's one similar to that I use:
void readintline(unsigned int* array, int* size) {
char buffer[101];
size=0;
char* in=buffer;
unsigned int* out=array;
fgets(buffer, 100, stdin);
do {
*out=0;
while(*in>='0') {
*out= *out* 10 + *in-'0';
++in;
}
if (*in)
++in; //skip whitespace
++out;
} while(*in);
size = out-array;
}
It will destroy your memory if there's more than 100 characters on a line, or more numbers than array can hold, but you won't get a faster routine to read in lines of unsigned ints.
On the other hand, if you want simple:
int main() {
std::string tmp;
while(std::getline(std::cin, tmp)) {
std::vector<int> nums;
std::stringstream ss(tmp);
int ti;
while(ss >> ti)
nums.push_back(ti);
//do stuff with nums
}
return 0;
}
I'd probably write the code something like this:
// Warning: untested code.
std::vector<int> read_line_ints(std::istream &is) {
std::string temp;
std::getline(is, temp);
std::istringstream buffer(temp);
int num;
std::vector<int> ret;
while (buffer>>num)
ret.push_back(num);
return ret;
}
In C++, you can use std::istringstream.
std::string nums = "1 20 300 4000";
std::istringstream stream(nums);
int a, b, c, d;
stream >> a >> b >> c >> d;
assert(a == 1 && b == 20 && c == 300 && d == 4000);
If you want to get it from the standard input, then do the same, but just use std::cin
std::cin >> a >> b >> c >> d;
The quick solution is to read them with scanf()
int array[1000];
int index = 0;
while ((index < 1000) && (scanf("%d", &tmp) == 1)) {
array[index++] = tmp;
}
This still needs a bit more validation ...
C++:
vector<int> ints;
while( !cin.eof() )
{
int t;
cin >> t;
if ( !cin.eof() )
ints.push_back(t);
}
Alternative (thx to Shahbaz)
int t;
vector<int> ints;
while(cin >> t)
ints.push_back(t);
In C++ it's extremely simple to read N integers separated by whitespace via stdin:
#include <iostream>
using namespace std;
const unsigned N = 5;
int main(void)
{
int nums[N];
for (unsigned i = 0; i < N; ++i)
cin >> nums[i];
cout << "Your numbers were:\n";
for (unsigned i = 0; i < N; ++i)
cout << nums[i] << " ";
cout << "\n";
return 0;
}