reading csv using atof() with c++ - c++

I was stuck in this problem, I tried to read the datas from my csv file.
I will put my output and source code below.
As you can see,I'm printing the value of tmp[i] first and then I use another array to store the value in column tmp[i].
But the outputs are wrong. It's value should be the same as tmp[i].
Hoping someone can help me deal with this.
output:
69
26
54
3
69
54.1442
54.6054
54.1772
double stockp1[1000];
double stockp2[1000];
double stockp3[1000];
double stockp4[1000];
int c=0,d=0,e=0,f=0;
while (getline(inFile, line))
{
vector<string> a = _csv(line);
stockp1[c++] = atof(a[tmp[0]].c_str());
stockp2[d++] = atof(a[tmp[1]].c_str());
stockp3[f++] = atof(a[tmp[2]].c_str());
stockp4[e++] = atof(a[tmp[3]].c_str());
}
for (int i = 0; i < 4; i++)
{
cout << tmp[i] << endl;
}
cout << stockp1[0] << endl;
cout << stockp2[0] << endl;
cout << stockp3[0] << endl;
cout << stockp4[0] << endl;
}
vector<string> _csv(string s)
{
vector<string> arr;
istringstream delim(s);
string token;
int c = 0;
while (getline(delim, token, ','))
{
arr.push_back(token);
c++;
}
return arr;
}

Related

I want this c++ program to find the the words starting with user entereed letter and print them using a new function

I want this c++ program to find the the words starting with user entereed letter and print them using a new function.but the thins is that it only finds 1st letter for the second time it runs ina loop and then , i dont know what happens ... I am a beginner please help me!
uncomment the line that are necessary
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getUserInput(string *filename, string *find)
{
cout << "file name : ";
cin >> *filename;
cout << "required character : ";
cin >> *find;
}
string* processFile(string fileName, string word, int *t, int *w, string found[])
{
fstream file;
int countIn = 0,
totaal = 0;
int *count = &countIn;
int *total = &totaal;
int i = 0;
string find; // the max length of the file should not exceed this value is if does please change it here.
file.open(fileName, ios::in);
if (file.is_open())
{
while (!file.eof())
{
file >> find;
totaal++;
if (word == find)
{
char a[100];
int s = find.size();
for (int j = 0; i < find.size(); j++)
{
string(1, find[i]);
}
found[i] = find;
i++;
countIn++;
}
}
}
else
cout << "!!!!invalid file name!!!!\n";
file.close();
//for (int i = 0, j = 0; i < totaal; i++)
//{
//
// cout << find[i] << '\t' << find[i][0] << endl;
//
// if (word == find[i][0])
// {
// cout << "i is " << i << endl;
// cout << "j is " << j << endl;
// cout << "Calculated i and j\n";
// found[j] = find[i];
// cout << "found[j] " << found[j] << "\nfind[i] " << find[i] << endl;
// j++;
// countIn++;
// cout << "Inside if\n";
// }
// cout << "outsidenside if\n";
//}
*t = *total;
*w = *count;
//cout << countIn << endl << totaal << endl;
//cout << *count << endl << *total<<endl;
return found;
}
void displayOutput(int total, int count, string wordlist[])
{
cout << "Total words in the file: " << total;
if (count != 0)
{
cout << "\nTotal " << count << " related words found in the file\n";
for (int i = 0; i < count; i++)
cout << i + 1 << "\t" << wordlist[i] << endl;
}
else
cout << "No matching case found\n";
}
int main()
{
string nameoffile;
string wordtofind;
string *ptr1 = &nameoffile;
string *ptr2 = &wordtofind;
string foundwords[] = { "" };
int occur = 0,
totalWords = 0;
int *occ = &occur;// occurence of the certain word
int *tot = &totalWords;// total wods in the file
getUserInput(ptr1, ptr2);
processFile(nameoffile, wordtofind, occ, tot, foundwords); //calling the processing function
displayOutput(occur, totalWords, foundwords);
return 0;
}

How to convert multiple numbers in a string into ints

I am confused as to how to take multiple strings that have numbers in them and convert them into an int. I have multiple lines of strings that are stored in data into ints and then insert them into a 2 dimensional arrays called values. A similar question was posted earlier on StackOverflow; however it does not seem to be working for me. I printed out what each line in data is, each string in data is as follows.
75
95 64
17 42 82
18 35 87 10
However when I output the numbers from value by using two for loops in main, it outputs as this.
75
0
0
0
95
64
0
0
95
64
0
0
17
42
82
0
17
42
82
0
18
35
87
10
18
35
87
10
0
0
0
0
I found that there are 8 columns and 8 elements in the array values when I printed the sizeof(values) and sizeof(values[0]); however, it appears that the program terminated as the last print statement, where I print hello does not occur. I provided the code I'm using below. I would like to know why this is occurring
and how I can fix it? Thanks.
//const char DELIMITER = ' ';
int **values, // This is your 2D array of values, read from the file.
**sums; // This is your 2D array of partial sums, used in DP.
int num_rows; // num_rows tells you how many rows the 2D array has.
// The first row has 1 column, the second row has 2 columns, and
// so on...
bool load_values_from_file(const string &filename) {
ifstream input_file(filename.c_str());
if (!input_file) {
cerr << "Error: Cannot open file '" << filename << "'." << endl;
return false;
}
input_file.exceptions(ifstream::badbit);
string line;
vector<string> data;
try {
while (getline(input_file, line)) {
data.push_back(line);
num_rows ++;
}
input_file.close();
} catch (const ifstream::failure &f) {
cerr << "Error: An I/O error occurred reading '" << filename << "'.";
return false;
}
for(int x = 0; x < data.size(); x++){
cout << data[x] << endl;
}
//https://stackoverflow.com/questions/1321137/convert-string-containing-several-numbers-into-integers
//Help on making multiple numbers in a string into seperate ints
values = new int*[num_rows];
vector<int> v;
for(int y = 0; y < data.size(); y++){
istringstream stream(data[y]);
values[y] = new int[y + 1];
int z = 0;
while(1) {
int n;
stream >> n;
if(!stream)
break;
values[y][z] = n;
z++;
}
z = 0;
}
sums = values;
return true;
}
int main(int argc, char * const argv[]) {
if (argc != 2) {
cerr << "Usage: " << argv[0] << " <filename>" << endl;
return 1;
}
string filename(argv[1]);
if (!load_values_from_file(filename)) {
return 1;
}
cout << sizeof(values) << endl;
cout << sizeof(values[0]) << endl;
for(int x = 0; x < sizeof(values); x++){
for(int y = 0; y < sizeof(values[x]); y++){
cout << values[x][y] << endl;
}
cout << endl;
}
cout << "hello" << endl;
return 0;
}
See this :
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string str;
ifstream fs("D:\\Myfolder\\try.txt", ios::in);
stringstream ss;
std::string item;
if (fs.is_open())
{
ss << fs.rdbuf();
str = ss.str();
cout << str << endl;
fs.close();
}
cout << "\n\n Output \n\n";
while (std::getline(ss, item, ' '))
{
cout << std::atoi(item.c_str()) <<" ";
}
return 0;
}

I think I am not understanding pointers fully, but why is there a difference in the outputs here?

Below I have a snippet of my code. Basically, I am wondering why there is a difference in output when I individually print contextFile[0] and contextFile[1] versus through a for loop.
In contextfile.txt (which is the value of target_file_name in this case), I have the following:
hickory dickory dot had a little farm you feel me.
Here is the code:
cin >> target_file_name;
ifstream fileExist(target_file_name);
if (fileExist)
{
int count = 0;
int contextSize = 1000;
int keySize = 1000;
char *contextFile;
char *keyFile;
contextFile = new char[contextSize];
keyFile = new char[keySize];
string command;
fileExist >> contextFile[count];
while (!fileExist.fail())
{
count++;
fileExist >> contextFile[count];
}
cout << "printing individual: " << contextFile[0] << contextFile[1];
cout << "Printing the contextfile array: " << endl;
for (int i = 0; i < count; i++)
{
cout << contextFile[count];
}
When I print individually, I get hi, which is the correct output.
When I print through the for loop, I just get straight ================.
Why is there a difference?
Because you print
cout << contextFile[count];
over and over again, instead of
cout << contextFile[i];
in your loop, resulting in undefined behavior, since contextFile[count] was never initialized.
It's because you are printing only one value inside the for loop.
for (int i = 0; i < count; i++) {
cout << contextFile[count];
}
You need to make changes in that
for (int i = 0; i < count; i++) {
cout << contextFile[i];
}
Your input file has 50 characters in it. So, after your reading loop is finished, count is 50, and contextFile[0] up to and including contextFile[49] have been populated with data.
You are then outputting the first two individual characters of contextFile[], which is fine.
Then you are running a loop through the first count characters of contextFile[], which is also fine. But on every loop iteration, you are outputting contextFile[50], which has not been populated with any valid data. You should be outputting contextFile[i] instead:
for (int i = 0; i < count; i++)
{
//cout << contextFile[count];
std::cout << contextFile[i];
}
That being said, I would suggest NOT using a char[] at all:
std::getline(std::cin, target_file_name);
std::ifstream theFile(target_file_name);
if (theFile)
{
std::vector<char> contextFile;
char ch;
theFile.seekg(0, std::ios_base::end);
size_t size = theFile.tellg();
theFile.seekg(0, std::ios_base::beg);
contextFile.reserve(size);
while (theFile >> ch)
{
contextFile.push_back(ch);
}
/* alternatively:
contextFile.reserve(size);
std::copy(
std::istream_iterator<char>(theFile),
std::istream_iterator<char>(),
std::back_inserter(contextFile)
);
*/
/* alternatively:
contextFile.resize(size);
theFile.read(&contextFile[0], size);
size = theFile.gcount();
contextFile.resize(size);
*/
std::cout << "printing individual: " << contextFile[0] << contextFile[1]" << std::endl;
std::cout << "Printing the contextfile array: " << std::endl;
for (int i = 0; i < contextFile.size(); i++)
{
std::cout << contextFile[i];
}
/* alternatively:
for (std::vector<char>::iterator iter = contextFile.begin(); iter != contextFile.end(); ++iter)
{
std::cout << *iter;
}
*/
/* alternatively:
std::copy(
contextFile.begin(),
contextFile.end(),
std::ostream_iterator<char>(std::cout)
);
*/
/* alternatively:
std::cout.write(&contextFile[0], contextFile.size());
*/

Loading Variable from a file

AT
4
5
6
7
#include<iostream>
#include<stdio.h>
#include <fstream>
using namespace std;
int main()
{
int data[4], a, b, c, d, e, f;
ifstream myfile;
myfile.open("tera.txt");
for (int i = 0; i < 4; i++)
{
myfile >> data[i];
}
myfile.close();
a = data[0];
b = data[1];
c = data[2];
d = data[3];
cout << a << "\t" << b << "\t" << c << "\t" << d << "\n";
return 0;
}
it takes AT also and give garbage value. how and where should i use ignore function to ignore AT Value.
And there is one thing more if there is another array given BT containing some value like this:
AT BT
how to store BT's all values under it in an array?
You just have to skip the first line. You can also add optional error handling, otherwise read may fail for all line.
if (!myfile)
{
cout << "can't open\n";
return 0;
}
string temp;
myfile >> temp;
cout << "first line: " << temp << endl;
for (int i = 0; i < 4; i++)
{
myfile >> data[i];
if (myfile.fail())
{
cout << "error\n";
myfile.clear();
myfile.ignore(1000000, '\n');
}
}

Reading from a file into an object?

I have a file of the format:
3 // num of tasks in taskset1
1 2 3 //priority for each task
10 20 30 //exec time, deadline , period
23 34.5 45
23 56 98
4 // num of tasks in taskset2
1 2 4 3//priority for each task
10 20 30 //exec time, deadline , period
23 34.5 45
23 56 98
34 54 100
......
I need to read the text file directly into a structure object taskset.
struct tasks
{
double wcet;
double deadline;
double period;
int priority;
};
struct tasksets
{
tasks task[100];
double num_tasks;
} taskset[100];
I am storing the contents in an array and then into objects which works fine. But since my file size is too huge, my program gets killed. I need to do without using the huge array. And instead of 100 different objects just use one object for the taskset. Any suggestions on how to do it?
int main(int argc, char* argv[])
{
double aa[1000][1000];
int u = 0;
int v = 0;
int i = 0;
int j = 0;
int k = 0;
string temp; // a temporary variable used to store string data
vector<vector<string>> tokens;
while (getline(cin, temp))
{
v = 0;
istringstream iss(temp);
vector<string> tokens_in_line;
while (iss >> temp)
{
double temp1 = atof(temp.c_str());
aa[u][v] = temp1;
v++;
tokens_in_line.push_back(temp);
}
u++;
if (!tokens_in_line.empty())
{
tokens.push_back(tokens_in_line);
}
}
cout << "Execution started" << endl;
for (i = 0; i < u; i = i + j)
{
cout << "Task set #" << setnum << endl;
taskset[setnum].num_tasks = aa[i][0];
cout << "Number of tasks: " << taskset[setnum].num_tasks << endl;
for (k = 0; k < taskset[setnum].num_tasks; k++)
{
taskset[setnum].task[k].priority = aa[i + 1][k];
taskset[setnum].task[k].wcet = aa[i + 2 + k][0];
taskset[setnum].task[k].deadline = aa[i + 2 + k][1];
taskset[setnum].task[k].period = aa[i + 2 + k][2];
cout << "Task " << k + 1 << ":";
cout << " Priority : " << taskset[setnum].task[k].priority;
cout << " WCET : " << taskset[setnum].task[k].wcet;
cout << " Deadline : " << taskset[setnum].task[k].deadline;
cout << " Period : " << taskset[setnum].task[k].period << endl;
}
j = k + 2;
setnum++;
}
return 0;
}
Yeah you can read directly into the variables of the class with the operator >>. use getline to read into each variable. The code I used before is below for you to see ho its done. Basically you want to create a class with those variable needing to be read into and then you want to instanciate it in the class or main whichever you doing and read the file then add each variable that way. see below where p is the instanciated class with variables.
string STRING;
string floor;
string toFloor;
ifstream infile;
infile.open("passenger requests.txt");
if (!infile)
{
cout << "no good file failed! \n" << endl;
}
while (infile.good())
{
for (int i = 0; i < 49; ++i)
{
getline(infile, STRING);
//Saves the line in STRING.
infile >> p[i].time;
getline(infile, floor, ',');
infile >> p[i].fromFloor;
getline(infile, toFloor, ',');
infile >> p[i].toFloor;
}
}
infile.close();
}
As Josh already pointed out, you can read your tokens into the variable directly instead of storing them in aa. By the way, aa being a double array of arrays is not a good choice for your integer tokens anyway.
Concerning the use of fixed-size arrays and crashing your program for too large input sets, I would instead go for either a std::list or std::vector for the tasksets and append new objects as needed.
Finally, your code doesn't compile as provided, I had to add a declaration for setnum and the necessary headers.
The main problem I see in your format - you have to read all priorities for all tasks in taskset before you can actually read tasks, if you can change format to store priority for each task at the same line where other details are - it would be better, anyway here is version which use less memory than your original one:
struct task {
double wcet;
double deadline;
double period;
int priority;
};
int main(int, char**) {
task currentTask;
std::string temp; // a temporary variable used to store string data
while (std::getline(std::cin, temp)) {
const int taskCount = atoi(temp.c_str()); // read number of tasks
// parse task priorities
int* priorities = new int[taskCount];
for (int i=0; i<taskCount; i++)
std::cin >> priorities[i];
// read actual tasks
for (int i=0; i<taskCount; i++) {
std::cin >> currentTask.wcet;
std::cin >> currentTask.deadline;
std::cin >> currentTask.period;
currentTask.priority = priorities[i];
std::cout << "Task " << (i + 1) << ":";
std::cout << " Priority : " << currentTask.priority;
std::cout << " WCET : " << currentTask.wcet;
std::cout << " Deadline : " << currentTask.deadline;
std::cout << " Period : " << currentTask.period << std::endl;
}
delete[] priorities;
}
return 0;
}