Xcode: Program ended with exit code: 255 - c++

I am trying to read a csv file into C++, but I kept got the message that "Program ended with exit code:255". I tried restart the Xcode, restart the Mac, but it did not work. Is anyone have the same problem?
Here is my code:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fstream>
using namespace std;
// defind the type of longitude and latitude as the key
typedef struct {
double lat;
double lon;
} location;
struct Stud{
location key;
string date;
double temp;
double concen;
string descrip;
};
int main()
{
int counter = 0;
string line;
Stud items;
ifstream file("data.csv");
if( !file.is_open()) {
cout << "File not found." << endl;
exit(-1);
}
while ( getline( file, line) ) { // To get the number of lines in the file
counter++;
}
Stud* item = new Stud[counter]; // Add number to structured array
for (int i = 0; i < counter; i++) {
file >> item[i].date >> item[i].key.lon>> item[i].key.lat>> item[i].temp >> item[i].concen >> item[i].descrip;
}
cout << item[1].date << endl;
file.close();
return 0;
}
I appreciate any help!

Related

Reading from input file and storing in array c++

I want to read from a file.txt that looks like this:
process_id run_time
T1 23
T2 75
Read each line and store integers of run time (tab separation)in an array
My problem now is to read the content of the file .. and how to get the integer after the tab separation?
thanks
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main ()
{
int process_id[100];
int run_time[100];
int arrival_time[100];
char quantum[50];
int switching;
char filename[50];
ifstream ManageFile; //object to open,read,write files
cout<< "Please enter your input file";
cin.getline(filename, 50);
ManageFile.open(filename); //open file using our file object
if(! ManageFile.is_open())
{
cout<< "File does not exist! Please enter a valid path";
cin.getline(filename, 50);
ManageFile.open(filename);
}
while (!ManageFile.eof())
{
ManageFile>>quantum;
cout << quantum;
}
//ManageFile.close();
return 0;
}
use C++, not C
don't use std::cin.getline, use std::getline (it works with std::string and is safer)
use a vector instead of hard-dimensioned arrays
use a vector of struct instead of "corresponding arrays"
don't use while (!stream.eof())
Here's a sample that might be helpful:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
struct Record {
int process_id;
int run_time;
int arrival_time;
};
int main() {
std::vector<Record> records;
int switching;
std::string filename;
ifstream infile;
while (!infile.is_open()) {
cout << "Please enter your input file: ";
std::getline(std::cin, filename);
infile.open(filename); // open file using our file object
cout << "File cannot be opened.\n";
}
std::string quantum;
std::getline (infile, quantum); // skip header row
while (std::getline(infile, quantum)) {
// e.g.
Record current;
std::istringstream iss(quantum);
if (iss >> current.process_id >> current.run_time >> current.arrival_time)
records.push_back(current);
else
std::cout << "Invalid line ignored: '" << quantum << "'\n";
}
}
You can try something like this:
while (!ManageFile.eof())
{
quantum[0] = 0;
ManageFile>>quantum;
if (strcmp(quantum, "0") == 0 || atoi(quantum) != 0)
cout << quantum << endl;
}
Of course, you need to include in the head
Use function ignore from istream [http://www.cplusplus.com/reference/istream/istream/ignore/]
while (!ManageFile.eof())
{
std::string process_id;
int run_time;
ManageFile >> process_id;
ManageFile.ignore (256, '\t');
ManageFile >> run_time;
}
Using fscanf instead of ifstream can make the job a lot easier.
char str[100];
int n;
....
fscanf(FILE * stream,"%s %d", str, &n);
You will get the string in str and integer in n.

C++ Getting values from file into array

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;
void make_array(ifstream& num, int (&array)[50]);
int main()
{
ifstream file; // variable controlling the file
char filename[100]; /// to handle calling the file name;
int array[50];
cout << "Please enter the name of the file you wish to process:";
cin >> filename;
cout << "\n";
file.open(filename);
if (file.fail()) {
cout << "The file failed to open.\n";
exit(1);
} else {
cout << "File Opened Successfully.\n";
}
make_array(file, array);
file.close();
return (0);
}
void make_array(ifstream& num, int (&array)[50])
{
int i = 0; // counter variable
while (!num.eof() && i < 50) {
num >> array[i];
i = i + 1;
}
for (i; i >= 0; i--) {
cout << array[i] << "\n";
}
}
I am trying to read values from a file to an array using fstream. When I try to display the contents of the array, I get 2 really big negative numbers, and then the contents of the file.
Any ideas what I did wrong?
Your use of num.get(array[i]) doesn't match any of its signatures. See get method description. What you want is this:
array[i] = num.get();
As discussed in the comments, you try to read an integer which is encoded as text. For this, you need to use operator>> (which reads any type encoded as string) instead of get (which reads a single byte):
num >> array[i];

error with reading data back out of a vector

this is my program for reading data from a text file and storing it into a vector, im having trouble compiling this, any suggesting would be great.
id like to in this example to call all the data for year and month.
im hoping its something simple ive missed.
#include <iostream>
#include <libscat.h>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
struct Weather
{
int year;
int month;
double tempmax;
double tempmin;
};
int main()
{
vector<Weather> data_weather;
string line;
std::ifstream myfile ("weatherdata.txt");
if (myfile.is_open())
{
while ( getline(myfile, line) )
{ int count = 0;
if (count > 8)
{
std::istringstream buffer(line);
int year, mm;
double tmax, tmin;
if (buffer >> year >> mm >> tmax >> tmin)
{
Weather objName = {year, mm, tmax, tmin};
data_weather.push_back(objName);
count++;
}
}
for (auto it = data_weather.begin(); it != data_weather.end(); it++){
std::cout << it->year << " " << it->month << std::endl;}
myfile.close();
}
else
{
cout << "unable to open file";
}
scat::pause("\nPress <ENTER> to end the program.");
return 0;
}
}
Here's a fixed version with explanation since there still wasn't any real answer.
#include <iostream>
#include <libscat.h>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
struct Weather
{
int year;
int month;
double tempmax;
double tempmin;
};
int main()
{
std::vector<Weather> data_weather;
std::string line;
std::ifstream myfile("weatherdata.txt");
if (myfile.is_open())
{
int count = 0; // you gotta put it in front of the while loop or you'll
// create a new variable and initialize it to 0 every time
// you enter the loop
while ( getline(myfile, line) )
{
// int count = 0; // placed it just before the loop
if ( count > 8)
{
std::istringstream buffer(line);
int year, mm;
double tmax, tmin;
if (buffer >> year >> mm >> tmax >> tmin)
{
Weather objName = {year, mm, tmax, tmin};
data_weather.push_back(objName);
// count++; // you're still inside the if (count > 8)
// you'd probably want to have it outsided the if statement
// instead.
}
}
++count; //the count from inside. it'll probably do what you wanted
//it to do here.
// you'll probably want to run the for loop AFTER the while loop
// when the data_weather vector got fully filled
}
// the for loop from inside the while now outside
for (auto it = data_weather.begin(); it != data_weather.end(); ++it)
{
std::cout << it->year << " " << it->month << std::endl;
myfile.close();
}
}
else
{
std::cout << "unable to open file";
}
scat::pause("\nPress <Enter> to end the program.");
return 0;
}

C++ program to read a txt file and sort data

I'm a physics PhD student with some experience coding in java, but I'm trying to learn C++.
The problem I'm trying to solve is to read in data from a .txt file and then output all the numbers > 1000 in one file and all those <1000 in another.
What I need help with is writing the part of the code which actually reads in the data and saves it to an array. The data itself is only separated by a space, not all on a new line, which is confusing me a bit as I don't know how to get c++ to recognise each new word as an int. I have canabalised some code I have got from various sources online-
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include<cmath>
using namespace std;
int hmlines(ifstream &a) {
int i=0;
string line;
while (getline(a,line)) {
cout << line << endl;
i++;
}
return i;
}
int hmwords(ifstream &a) {
int i=0;
char c;
a >> noskipws >> c;
while ((c=a.get()) && (c!=EOF)){
if (c==' ') {
i++;
}
}
return i;
}
int main()
{
int l=0;
int w=0;
string filename;
ifstream matos;
start:
cout << "Input filename- ";
cin >> filename;
matos.open(filename.c_str());
if (matos.fail()) {
goto start;
}
matos.seekg(0, ios::beg);
w = hmwords(matos);
cout << w;
/*c = hmchars(matos);*/
int RawData[w];
int n;
// Loop through the input file
while ( !matos.eof() )
{
matos>> n;
for(int i = 0; i <= w; i++)
{
RawData[n];
cout<< RawData[n];
}
}
//2nd Copied code ends here
int On = 0;
for(int j =0; j< w; j++) {
if(RawData[j] > 1000) {
On = On +1;
}
}
int OnArray [On];
int OffArray [w-On];
for(int j =0; j< w; j++) {
if(RawData[j]> 1000) {
OnArray[j] = RawData[j];
}
else {
OffArray[j] = RawData[j];
}
}
cout << "The # of lines are :" << l
<< ". The # of words are : " << w
<< "Number of T on elements is" << On;
matos.close();
}
But if it would be easier, i'm open to starting the whole thing again, as I don't understand exactly what all the copied code is doing. So to summarise, what I need is it to-
Ask for a filepath in the console
Open the file, and store each number (separated by a space) as an element in a 1D array
I can manage the actual operations myself I think, if I could just get it to read the file the way I need.
Thanks very much
Using C++11 and the Standard Library makes your task fairly simple. This uses Standard Library containers, algorithms, and one simple lambda function.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <vector>
int main()
{
std::string filename;
std::cout << "Input filename- ";
std::cin >> filename;
std::ifstream infile(filename);
if (!infile)
{
std::cerr << "can't open " << filename << '\n';
return 1;
}
std::istream_iterator<int> input(infile), eof; // stream iterators
std::vector<int> onvec, offvec; // standard containers
std::partition_copy(
input, eof, // source (begin, end]
back_inserter(onvec), // first destination
back_inserter(offvec), // second destination
[](int n){ return n > 1000; } // true == dest1, false == dest2
);
// the data is now in the two containers
return 0;
}
Just switch the type of variable fed to your fistream, created from new std:ifstream("path to file") into a int and c++ will do the work for you
#include <fstream> //input/output filestream
#include <iostream>//input/output (for console)
void LoadFile(const char* file)
{
int less[100]; //stores integers less than 1000(max 100)
int more[100]; //stores integers more than 1000(max 100)
int numless = 0;//initialization not automatic in c++
int nummore = 0; //these store number of more/less numbers
std::ifstream File(file); //loads file
while(!file.eof()) //while not reached end of file
{
int number; //first we load the number
File >> number; //load the number
if( number > 1000 )
{
more[nummore] = number;
nummore++;//increase counter
}
else
{
less[numless] = number;
numless++;//increase counter
}
}
std::cout << "number of numbers less:" << numless << std::endl; //inform user about
std::cout << "number of numbers more:" << nummore << std::endl; //how much found...
}
This should give you an idea how should it look like(you shoudnt use static-sized arrays tough) If you got any probs, comment back
Also, please try to make nice readable code, and use tabs/ 4 spaces.
even though its pure C, this might give you some hints.
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#define MAX_LINE_CHARS 1024
void read_numbers_from_file(const char* file_path)
{
//holder for the characters in the line
char contents[MAX_LINE_CHARS];
int size_contents = 0;
FILE *fp = fopen(file_path, "r");
char c;
//reads the file
while(!feof(fp))
{
c = fgetc(fp);
contents[size_contents] = c;
size_contents++;
}
char *token;
token = strtok(contents, " ");
//cycles through every number
while(token != NULL)
{
int number_to_add = atoi(token);
//handle your number!
printf("%d \n", number_to_add);
token = strtok(NULL, " ");
}
fclose(fp);
}
int main()
{
read_numbers_from_file("path_to_file");
return 0;
}
reads a file with numbers separated by white space and prints them.
Hope it helps.
Cheers

how to insert data from a text file into an array of struct

I need to read data from a text file, and insert the data in an array of struct. The data file is in the following format:
productname price quantity
my main concern is to read the product name, which consist of one, and two words. Should I approach product name as a c-string or as a string literal?
any help appreciated
#include <iostream>
#include <fstream>
using namespace std;
const int SIZE = 15; //drink name char size
const int ITEMS = 5; //number of products
struct drinks
{
char drinkName[SIZE];
float drinkPrice;
int drinkQuantity;
};
int main()
{
//array to store drinks
drinks softDrinks[ITEMS];
//opening file
ifstream inFile;
inFile.open("drinks.txt");
char ch;
int count = 0; //while loop counter
if(inFile)
{
while(inFile.get(ch))
{
//if(isalpha(ch)) { softDrinks[count].drinkName += ch; }
//if(isdigit(ch)) { softDrinks[count].drinkPrice += ch; }
cout << ch;
}
cout << endl;
count++;
}
else
{
cout << "Error opening file!\n";
system("pause");
exit(0);
}
system("pause");
return 0;
}
Since you ask for "any help", here's my view: Forget everything you wrote, and use C++:
#include <fstream> // for std::ifstream
#include <sstream> // for std::istringstream
#include <string> // for std::string and std::getline
int main()
{
std::ifstream infile("thefile.txt");
std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
std::string name;
double price;
int qty;
if (iss >> name >> price >> qty)
{
std::cout << "Product '" << name << "': " << qty << " units, " << price << " each.\n";
}
else
{
// error processing that line
}
}
}
You could store each line of data in a std::tuple<std::string, int, double>, for example, and then put those into a std::vector as you go along.