Problems with fstream - c++

I'm writing a vector array to an ofstream file, however certain values aren't getting written, I.E.:
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main (){
char * hold = new char [100];
vector<double> fx(2049);
ifstream inputFile;
ofstream myFile;
inputFile.open("data.txt");
myFile.open("test.txt");
for (int c=0; c<2049; c++){
inputFile.getline(hold, 100);
fx[c] = atof(hold);
}
for (int c=0; c<2049; c++){
myFile << fx[c] << "\n";
}
}
Within fx, the second half is all equal to 0. (fx[1024] through fx[2048]==0). Within test.txt however, none of these 0 values are present, on the carriage return is applied. Any thoughts?
Thanks! (New to the formatting of these questions... any tips to make this more understandable would be appreciated.)
Note: I realize this program is rather redundant. The actual program has a great deal more functionality to it, this is just an area that is working incorrectly.

Try this
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#define MAX_FILE_LINES 2048
using namespace std;
//genarate random double number
double fRand()
{
double fMin = 100, fMax = 200;
double f = (double)rand();
return fMin + (f / (fMax - fMin));
}
//init file (if you need to create sample file with list of double numbers, you can use this function)
void fileInit(){
ofstream sourceFile;
sourceFile.open("D:\\source.txt");
if (sourceFile.is_open())
{
for (int i=0; i<MAX_FILE_LINES; i++){
sourceFile << fRand() << endl;
}
}
}
int main (){
string buffer;
vector<double> fx(MAX_FILE_LINES);
ifstream sourceFile;
ofstream destinationFile;
sourceFile.open("D:\\source.txt");
destinationFile.open("D:\\destination.txt");
//reading file lines to vector
int lineCount =0;
if (sourceFile.is_open())
{
while ( sourceFile.good() )
{
getline (sourceFile,buffer);
fx[lineCount] = atof(buffer.c_str());
lineCount++;
if (lineCount == (MAX_FILE_LINES-1)){
break;
}
}
sourceFile.close();
}
//write lines to new file
if (destinationFile.is_open())
{
for (int i=0; i<MAX_FILE_LINES; i++){
destinationFile << fx[i] << endl;
}
}
}

Why screw with handroll buffers for one-offs? You can't save a millionth of what it costs to think about cycles here, there's not enough waste to recoup.
Think about eliminating needless statements and unchecked failures first.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<float> data;
{
ifstream ids("source.txt",ios_base::in);
int linenr = 0;
for ( string line ; getline(ids,line) ; ) {
++linenr;
decltype(data)::value_type x;
istringstream s(line);
if ( s >> x )
data.push_back(x);
else
cerr << "crap line "<<linenr<<" ignored: " << line << '\n';
}
}
ofstream ods("object.txt");
for ( auto x : data )
ods << x << '\n';
}

Related

Store a column from csv excel file to a vector double variable C++

I have a csv file in Excel that has a column of double data. I am trying to read that column and store the values in a vector variable using a while loop. I tried to use getline and then convert them into a double using stod.
The column has more values, but this is how the csv file looks like:
A
B
51.32
53.62
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream myFile("CData.csv");
int i= 0;
string val;
std::vector<double> y;
while (getline(myFile, val, ',')) {
y.push_back(stod(val));
cout << "test: " << y.at(i);
i++;
}
return 0;
}
I'm not sure what I'm doing wrong. Somehow, there is no output on the console app. I tried it with string ang it worked but when I try to convert to a double, it doesn't. Is there another way to do this, or did I miss something in the code? Thanks, I'm new to coding.
You need to first parse the line and then look at the line for comma separated data. Also you need to chek if data is digits or not.
Here is an example:
#include <iostream>
#include <fstream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
using namespace std;
int main()
{
ifstream myFile("CData.csv", std::ios::in);
int i= 0;
string val;
std::string line;
std::vector<double> y;
while (getline(myFile, line))
{
std::stringstream sstr(line);
while (getline(sstr, val, ','))
{
bool flag = true;
for (auto c : val)
if (!isdigit(c))
flag = false;
if (flag){
y.push_back( std::stod(val));
std::cout << "number: " << y.at(i) << std::endl;
i++;
}
else std::cout << "not number: " << val << std::endl;
}
}
return 0;
}
Good luck!

trying to add words from text file to a vector but keep getting thrown 'std::out_of_range'

trying to add words from this text file but keep getting thrown an out of range error. I think the error lies somehwere in the loops but havent been able to figure out why it isnt working. Help would be greatly appreciated
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct WordCount{
string word;
int count;
};
int main () {
vector<WordCount> eggsHam;
ifstream readFile ("NewTextDocument.txt");
int counter = 0;
int holder;
string lineRead;
WordCount word;
if(readFile.is_open()){
//add all the words into a vector
while (getline(readFile, lineRead)){
holder = counter;
for(int i = 0; i < lineRead.length(); ++i) {
if (lineRead.at(i) != ' ') {
++counter;
}
if (lineRead.at(i) != ' ') {
for (int k = 0; k < (counter - holder); ++k) {
word.word.at(k) = lineRead.at(holder + k);
}
eggsHam.push_back(word);
++counter;
}
}
}
readFile.close();
}
else cout << "Unable to open file";
return 0;
}
Your code is way to complicated. To read all words (=space-seperated thingies) into a std::vector<std::string> simply do:
#include <cstdlib>
#include <vector>
#include <string>
#include <iterator>
#include <fstream>
#include <iostream>
int main()
{
char const *filename = "test.txt";
std::ifstream is{ filename };
if (!is.is_open()) {
std::cerr << "Couldn't open \"" << filename << "\" for reading :(\n\n";
return EXIT_FAILURE;
}
std::vector<std::string> words{ std::istream_iterator<std::string>{ is },
std::istream_iterator<std::string>{} };
for (auto const &w : words)
std::cout << w << '\n';
}

C++ File I/O and Pointers

I tried to create a program that uses an input file 'cardList.txt' that contains:
Schmidt, Helga
Alvarez, Ruben
Zowkowski, Aaron
Huang, Sun Lee
Einstein, Beverly
and I wanted to sort this alphabetically by last name.
main:
#include <iostream>
#include <fstream>
#include <string>
#include "insertsortFunct.h"
using namespace std;
int main(void){
ifstream inData;
ofstream outData;
const int listSize = 5;
char cardList[listSize][25];
instruct();
openFile(inData, outData);
buildList(cardList, inData);
inData.close();
sortList(cardList, listSize);
cout << endl << "Your list is sorted" << endl;
writeFile(cardList, outData);
outData.close();
return 0;
}
I defined these functions in a separate file:
#include "insertsortFunct.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
void instruct(void){
cout << "The program insertSort.cpp reads the file, cardList.txt " <<
"into an array and" << endl;
cout << "sorts the array using the selection sort algorithm." << endl;
cout << "The sorted array is written to a file named cardList.srt." <<
endl;
}
void openFile(ifstream& inputFile, ofstream& outputFile){
inputFile.open("cardsList.txt");
if(!inputFile.is_open())
exit(1);
outputFile.open("cardsList.srt");
if(!outputFile.is_open())
exit(1);
}
void buildList(char (*array)[25], ifstream& inputFile){
for (int i = 0; i < 5; i++)
inputFile >> array[i];
}
void sortList(char (*list)[25], int length){
int firstOutOfOrder, location;
char temp[25];
for (firstOutOfOrder = 1; firstOutOfOrder < length; firstOutOfOrder++){
location = firstOutOfOrder;
while ( location > 0 && list[location - 1] > list[location]){
temp[25] = list[location][25];
list[location][25] = list[location - 1][25];
list[location - 1][25] = temp[25];
location--;
}
}
}
void writeFile(char (*array)[25], ofstream& outputFile){
for (int i = 0; i < 5; i++)
outputFile << array[i];
}
However my program only prints the instruct(); statements and nothing else appears to happen. This program is supposed to a create a file cardList.srt with the sorted list and that does not appear in my directory after compiling.
Either inputFile.is_open() or outputFile.is_open() return false and hence exit() is called.

How to continue to read a binary file with .read?

I'm trying to read a binary file that contains a 1501-by-1501 matrix of double, and plug it in an Eigen matrix. Here is my code:
#include <fstream>
#include <iostream>
#include <Eigen/Dense>
#include <string>
using namespace std;
using namespace Eigen;
int main()
{
MatrixXd B(1501, 1501);
ifstream inputFile;
double toread;
inputFile.open("/path/to/bathymetry_S1000s2500s_E65d1000s65d2500s.bin",
ios::out | ios::in | ios::binary);
if (!inputFile) {
cout << "The file can't be opened.\n";
exit(10);
} else {
for (int i2 = 0; i2 < 1501; i2++) {
for (int i1 = 0; i1 < 1501; i1++) {
inputFile.read( reinterpret_cast<char*>( &toread ),
sizeof(toread) );
inputFile >> toread;
B(i1, i2) = toread;
}
}
inputFile.close();
}
cout << "Max value:" << B.maxCoeff() << endl; // Just to check the result
cout << "Mean Value:" << B.mean() << endl; // The same
}
My problem is that, when I run the code, my matrix B is actually filled only with the very first value of the inputFile, which is -4502, which will then be given by the two cout. (All the elements of the matrix are -4502). How can I make the compiler understand that I want it to continue reading the inputFile after the previous value, instead of starting from the beginning at each loop-step?

How to write a series of float from text using fstream

Example ABC.txt
10.f 30.2f 20.f
I want to retrieve those information and store inside my array. However i am unsure how to do it.
I dont understand what is
Then (if good), it calls num_get::get (using the stream's selected locale) to perform both the extraction and the parsing operations, adjusting the stream's internal state flags accordingly. Finally, it destroys the sentry object before returning.
std::fstream filestr("ABC.txt", std::fstream::in);
if(!filestr.good()) //Logical error on i/o operation
{
//Unable to process
filestr.close();
return;
}
unsigned index= 0;
unsigned count= 0;
while(filestr.good())
{
float buffer= 0.f;
filestr >> std::skipws >> buffer;
score[index]= buffer;
++index;
}
filestr.close();
There are a number of ways to do this. One way is using stringstreams, in combination with vectors and strings:
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
#include <vector>
using namespace std;
int main() {
std::ifstream filestr("C:\\nums.txt", std::fstream::in);
std::vector<double> numbers;
if (!(filestr.good())) {
std::cout << "BAD FILE" << std::endl;
exit(0);
}
else {
std::string temp;
double d = 0.0;
while(std::getline(filestr, temp)) {
std::istringstream iss(temp);
while(std::getline(iss, temp, ' ')) {
std::istringstream ist(temp);
ist >> f;
numbers.push_back(f);
}
}
}
//see that the vector has information in it
for (int i = 0; i < numbers.size(); i++) {
std::cout << numbers[i] << std::endl;
}
filestr.close();
return 0;
}
One thing to note is that you could also use iterators here, but that's something you could implement for yourself.
Super simple with istream_iterator. There is only one tricky bit in the code below. The vector constructor call needs an extra set of parens around the first argument to avoid the Most Vexing Parse.
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;
int
main (int argc, char** argv)
{
for (int i = 1; i < argc; ++i) {
ifstream in (argv[i]);
if (!in) {
cerr << "Failed to open " << argv[i] << endl;
continue;
}
vector<double> nums ((istream_iterator<double> (in)), istream_iterator<double> ());
copy (nums.begin (), nums.end (), ostream_iterator<double> (cout, "\n"));
}
return 0;
}