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;
}
Related
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 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';
}
I'm a beginner in c++ and required to write a c++ program to read and print a csv file like this.
DateTime,value1,value2
12/07/16 13:00,3.60,50000
14/07/16 20:00,4.55,3000
May I know how can I proceed with the programming?
I manage to get the date only via a simple multimap code.
I spent some time to make almost (read notice at the end) exact solution for you.
I assume that your program is a console application that receives the original csv-file name as a command line argument.
So see the following code and make required changes if you like:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <string>
std::vector<std::string> getLineFromCSV(std::istream& str, std::map<int, int>& widthMap)
{
std::vector<std::string> result;
std::string line;
std::getline(str, line);
std::stringstream lineStream(line);
std::string cell;
int cellCnt = 0;
while (std::getline(lineStream, cell, ','))
{
result.push_back(cell);
int width = cell.length();
if (width > widthMap[cellCnt])
widthMap[cellCnt] = width;
cellCnt++;
}
return result;
}
int main(int argc, char * argv[])
{
std::vector<std::vector<std::string>> result; // table with data
std::map<int, int> columnWidths; // map to store maximum length (value) of a string in the column (key)
std::ifstream inpfile;
// check file name in the argv[1]
if (argc > 1)
{
inpfile.open(argv[1]);
if (!inpfile.is_open())
{
std::cout << "File " << argv[1] << " cannot be read!" << std::endl;
return 1;
}
}
else
{
std::cout << "Run progran as: " << argv[0] << " input_file.csv" << std::endl;
return 2;
}
// read from file stream line by line
while (inpfile.good())
{
result.push_back(getLineFromCSV(inpfile, columnWidths));
}
// close the file
inpfile.close();
// output the results
std::cout << "Content of the file:" << std::endl;
for (std::vector<std::vector<std::string>>::iterator i = result.begin(); i != result.end(); i++)
{
int rawLen = i->size();
for (int j = 0; j < rawLen; j++)
{
std::cout.width(columnWidths[j]);
std::cout << (*i)[j] << " | ";
}
std::cout << std::endl;
}
return 0;
}
NOTE: Your task is just to replace a vector of vectors (type std::vector<std::vector<std::string>> that are used for result) to a multimap (I hope you understand what should be a key in your solution)
Of course, there are lots of possible solutions for that task (if you open this question and look through the answers you will understand this).
First of all, I propose to consider the following example and to try make your task in the simplest way:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string str = "12/07/16 13:00,3.60,50000";
stringstream ss(str);
vector<string> singleRow;
char ch;
string s = "";
while (ss >> ch)
{
s += ch;
if (ss.peek() == ',' || ss.peek() == EOF )
{
ss.ignore();
singleRow.push_back(s);
s.clear();
}
}
for (vector<string>::iterator i = singleRow.begin(); i != singleRow.end(); i++)
cout << *i << endl;
return 0;
}
I think it can be useful for you.
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';
}
I can get getline() to work with cin (getline(cin,line)), but when I open a stream, it won't read the line from the file. The file contains a list of elements from the periodic table.
for Example:
H
He
O
etc...
EDIT:
However, when I try to cout the newly read line, it doesn't put it into var symbol at the line:
cout << "symbol: " << symbol << endl;
It doesn't give me anything out, but it should return the first element (H).
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void print(vector <string> x)
{
cout << "list of elements:" << endl;
for (int i = 0; i < x.size(); ++i)
{
cout << x[i] << endl;
}
}
int main(int argc, char** argv)
{
string symbol;
vector <string> elementlist;
ifstream readin;
readin.open("Elements.txt");
getline(readin,symbol);
cout << "symbol: " << symbol << endl;
while (!readin.good())
{
elementlist.push_back(symbol);
getline(readin,symbol);
}
print (elementlist);
return 0;
}
I'd do it something like this:
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
class line {
std::string data;
public:
friend std::istream &operator>>(std::istream &is, line &l) {
std::getline(is, l.data);
return is;
}
operator std::string() const { return data; }
};
int main() {
std::ifstream readin("Elements.txt");
// Initialize vector from data in stream:
//
std::vector<std::string>
element_list((std::istream_iterator<line>(readin)),
std::istream_iterator<line>());
// write data from vector to cout:
//
std::copy(element_list.begin(), element_list.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}
As I stated in my comment, your loop condition is wrong.
while (!readin.good())
{
elementlist.push_back(symbol);
getline(readin,symbol);
}
As it turns out, you want to loop using the condition readin.good(). Since !readin.good() will evaluate to false, you never actually enter the loop.