Read a .dat File and create an array C++ - c++

I try to read a .dat file with a list of coordinates X and Y. My code work to count the lines in the file but it doesn't work to read the coordinates correctly. In the output just show me the number of lines in the .dat file, but it doesn't show me the coordinates. .dat file has 2 column and more than 5 rows (I have many files with different amount of coordinates). Any help is super welcome, i am very new in C++.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main() {
std::vector<int> numbers;
ifstream fileB;
const int SIZE=10;
char filas_dat [SIZE];
fileB.open("Verticesfixed_cell1slc44.dat");
std::string line;
int counter=0;
while (getline(fileB, line)) //contador de filas
{
++counter;
}
if(!fileB.good())
{
int current_number = 0;
while (fileB >> current_number){
numbers.push_back(current_number);}
fileB.close();
cout << "The numbers are: ";
for (int count = 0; count < numbers.size(); count++){
cout << numbers[count] << " ";}
cout << endl;
}
else
{
cout << "Error!";
}
return 0
}

The problem is that after you've counted the number of lines you are at the end of the file, so there is nothing more to read. A file doesn't reposition itself back to the beginning automatically. You have to tell the file to go back to the beginning.
A second similar problem is that when you get to the end of your file the getline function fails (because there's nothing more to read). That puts your file into an error state when nothing will work until you clear the error state.
Finally the call to !fileB.good() is unecessary. The file will never be good at this point, again this is because getline has failed.
Try this code
while (getline(fileB, line)) //contador de filas
{
++counter;
}
fileB.clear(); // clear the error state
fileB.seekg(0); // go back to the beginning of the file
int current_number = 0;
while (fileB >> current_number)
{
numbers.push_back(current_number);
}

Related

stock data from file into arrays c++

I have this specific code to read integers from a text file:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
bool contains_number(const string &c);
int main()
{
int from[50], to[50];
int count = 0;
{
string line1[50];
ifstream myfile("test.txt");
int a = 0;
if (!myfile)
{
cout << "Error opening output file" << endl;
}
while (!myfile.eof())
{
getline(myfile, line1[a]);
if (contains_number(line1[a]))
{
count += 1;
myfile >> from[a];
myfile >> to[a];
//cout << "from:" << from[a] << "\n";
//cout << "to:" << to[a] << "\n";
}
}
}
return 0;
}
bool contains_number(const string &c)
{
return (c.find_first_of("1:50") != string::npos);
}
I need to stock these values of from[] and to[] in 2 arrays to use them n another function, I tried to create 2 arrays in a simple way and affect the values for example:
int x[], y[];
myfile >> from[a];
for(int i=0; i<50;i++)
{
x[i] = from[i];
}
but it doesn't work. It seems that this way is only to read and display and a value in from will be deleted once another value comes.
Any help?
Thanks.
You're not incrementing your array index a in your loop. This results in line[0], to[0] and from[0] to be overwritten for every line in the file where contains_number returns true.
There is no reason for you to save your lines into memory. You can just process your lines as you go through the file (i.e. create a string line variable in your while loop).
Make sure you properly close your file handle.
Aside from that you should check your index bounds in the loop (a < 50), else you might be writing out of bounds of your arrays if your file has more numbers than 50.
A better solution yet would be to use vectors instead of arrays, especially if your file may contain any number of numbers.

Displaying contents of vector

I am having trouble displaying the contents of a vector. I am unsure whether it is the way I read in the values from the text file, or whether my display function is just not working.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
string line;
int n,length;
std::vector<int>arr1;
fstream file("t1.txt");
if(file.is_open())
{
while (getline(file,line))
{
cout << line << endl;
}
file << line;
length = line.length();
while(file >> n)
arr1.push_back(n);
for(int i =0; i < (int)arr1.size(); i++)
cout << arr1.at(i) << endl;
}
return 0;
}
Any help would be greatly appreciated.
the text file contains "5 2 5 5 -1 7 2 5 3 5 2 -2"
I suppose you have a problem with vector building (reading values from file to vector). You should delete (or comment) expression with getline, as well as writing line back to file (file << line), and use only file >> n.
Try the following shortened version of your program
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
string line;
int n;
std::vector<int> arr1;
fstream file("t1.txt");
if(file.is_open())
{
while(file >> n)
arr1.push_back(n);
for(int i =0; i < (int)arr1.size(); i++)
cout << arr1.at(i) << endl;
file.close();
}
return 0;
}
Problem of your initial code is that after you read line from your file (that comprises only one line) next reading (whether it is file >> ... or getline(...)) will provide no data because END OF FILE. To read data from file again you should re-open it
...
length = line.length();
file.close();
file.open("t1.txt");
while(file >> n)
arr1.push_back(n);
...
or rewind to the beginning
...
length = line.length();
file.clear();
file.seekg(0, ios_base::beg);
while(file >> n)
arr1.push_back(n);
...
But you should understand, that writing to file stream does not provide desired effect - the recorded data will be available only after transfer written data from the buffer to the file (in the general case, after the file closing).
EDIT:
Also I want to add, that C++ allows input to and output from vector without additional loops, just consider the following example
if(file.is_open())
{
// filling vector from the stream
istream_iterator<int> it(file); // iterator for int values in file
istream_iterator<int> eos; // end of straem
arr1.insert(arr1.begin(), it, eos);
// output vector to the stream (cout = standard output stream)
ostream_iterator<int> oit (cout,"\n"); // "\n" = new line is a separator for output
// also " " or any other separator can be used
copy(arr1.begin(), arr1.end(), oit);
}

C++ while, for and array

Hey guys I stuck working on an assignment in which I asked to write a program that lists the contents of a file.
#include<iostream>
#include<fstream>
using namespace std;
int main() {
string array[5];
ifstream infile("file_names.txt");
int x=0;
while(infile>>array[x++]){
for(int i=0;i<=x;i++){
infile >> array[i];
cout << array[i] << endl;}}
}
basically I have a file named "file_names.txt" that contains three strings and I want my program to list them.
you don't need two loops.
int main() {
int array_size=5;
string array[array_size];
ifstream infile("file_names.txt");
int x=0;int i=0;
while(i<array_size && infile>>array[i]){ //order is important here
cout << array[i] << endl;
i++;
}
}
Your assignment was
an assignment in which I asked to write a program that lists the contents of a file.
One way of printing the contents of a file could be
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fin("my_file.txt", ios::in); // open input stream
if(!fin){ // check state, that file could be successfully opened
printf("Error opening file.");
return 1;
}
while(fin.peek() != EOF){
cout << (char)fin.get();
}
fin.close(); // close input stream
return 0;
}
This code demonstrates some basic C++ functionality like
opening an input stream, checking the state of the input stream and reading the contents character by character. Try to understand each step.
I know I can get to the same result like this
string array[50];
ifstream infile("file_names.txt");
for(int i=0; **i<3**; i++){
infile >> array[i];
cout << array[i] <<endl;}
But the whole point is to use a while loop because there might be more or less than 3 items

Reading in a text file from a command line and storing the content of the file into a c-string

I am learning C++ in one of my classes and I am having difficulties storing the content of a .txt file into a c string.
I have figured out how to validate that the .txt file exists but when I try storing the characters into a c-string it crashes.
This is my most recent attempt:
char * fileContent[MAX_SIZE];
ifstream ifile(argv[1]);
while (int i = 0 < MAX_SIZE)
{
ifile >> fileContent[i];
cout << fileContent[i];
if (ifile.eof())
break;
i++;
}
ifile.close();
Every-time the console gets to the loop it crashes. Are there any suggestions to help make this work?
I need it to be a c-string so that I can run the c-string through other functions. I am still pretty new to C++.
The assignment states: "Reads a text file into memory, one byte at a time"
I hope what I am trying to do is this.
Thank you
You can use the following code to read from a text file and save the string as a C-string. The output file (output.txt) contains the c-string output.
#include <string>
#include <iostream>
#include <fstream>
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
char *out_c_string;
char ch;
int index=0;
while(cin >> ch)
out_c_string[index++] = ch;
for(int i=0; i<index; i++)
cout << out_c_string[i]; // the c string of the file :)
return 0;
}
There were few bugs in your code, try this:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int MAX_SIZE = 128;
int main(int argc, char* argv[])
{
char fileContent[MAX_SIZE]; //bad idea never do that!
// use an std::vector<char> instead!
// and reverse a minimum amount of chars
// using `reserve` if you are after performance
ifstream ifile(argv[1]);
int i = 0;
while (i < MAX_SIZE)
{
ifile >> fileContent[i];
cout << fileContent[i];
if (ifile.eof())
break;
i++;
}
ifile.close();
}
Combining everyones answers, I got this as my function:
void get_file_info(char * argv, char (&fileContent) [MAX_SIZE], int & filesize ){
freopen(argv, "r", stdin);
char ch;
int index = 0;
while (cin >> noskipws >> ch)
fileContent[index++] = ch;
cout << endl << index << endl;
#if SHOW_DEBUG_CODE
for (int count = 0; count < index; count++)
cout << fileContent[count];
#endif
fclose(stdin);
}
It seems to work just fine. I will look into vectors my next free time but for right now, I am going to continue with char array.
Thank you for your suggestions.
I would do this. It's more general to cope with any size file.
void ReadFile(char*file,char**buff,int*size){
// Open file as binary putting file position at the end
ifstream is(file,ios::binary|ios::ate);
// Get the current file position, which is the file end
*size=is.tellg();
// Put file pointer back at the start
is.seekg(0,ios::beg);
// errors
if (!*size){
cout<<"Unable to open input file or file empty\n";
exit(9);
}
// allocate a buffer one bigger to allow for zero terminator
*buff=new char[*size+1];
// read the whole file in one hit
is.read(*buff,*size);
// Done. So close and zero delimit data.
is.close();
*(*buff+*size)=0;
}

Fill an array with getline loop

Would like to fill an array one line at a time from the file "Hello.cpp". However if I do it the way below I fill the entire file [w] times instead of just grabbing one line from the file for each iteration of i.
If I remove the { } from getline then the array is filled with the last line of "Hello.cpp" [w] times.
I am not sure how to get a new [i] each time from the Hello.cpp file.
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main() {
int w=0;
ifstream in("Hello.cpp");
string s;
while(getline(in, s))
w=w+1; //first count the number of lines in the file for the array
string a[w];//make an array big enough for the file
for(int i = 0; i < w ; i++) {
ifstream in("Hello.cpp");
string s;
while(getline(in, s)){
a[i] = s;
cout << i + 1 << " " << s << endl;
}
}
I would close your file before reopening it (best practice).
Looks to me like you need to move your file open (ifstream constructor) outside of your for (do you really want to open the file w times)? Since you bother to count the lines first don't you really want something like this:
ifstream in1("Hello.cpp");
for(int i = 0; i < w ; i++) {
getline(in1, a[i]);
cout << i + 1 << " " << a[i] << endl;
}