Scanning information from file in c++ - c++

I have a file with the following information:
INTERSECTIONS:
1 0.3 mountain and 1st
2 0.9 mountain and 2nd
3 0.1 mountain and 3rd
How do I scan in c++ so that it scans the first number and stores it in an int, then scans the next number and stores it separately, then stores the name of the streets in an a string? I just switched from c so I know how to do it in C just by using
fscanf("%d %lf %s", int, float, string);
or
fgets
with strings but don't know how to do this in C++. Any help would be appreciated
main:
#include<iostream>
#include<list>
#include <fstream>
#include<cmath>
#include <cstdlib>
#include <string>
#include "vertex.h"
#include "edge.h"
#include "global.h"
using namespace std;
int main ( int argc, char *argv[] ){
if(argc != 4){
cout<< "usage: "<< argv[0]<<"<filename>\n";
}
else{
ifstream map_file (argv[3]);
if(!map_file.is_open()){
cout<<"could not open file\n";
}
else{
std::string line;
std::ifstream input(argv[3]);
int xsect;
int safety;
std:string xname;
std::list<vertex> xsection;
std::list<edge> EdgeList;
while (std::getline(input, line))
{
std::istringstream iss(line);
iss >> xsect >> safety;
std::getline(iss, xname);
}
}
}
}

It's enough with std::getline and std::istringstream and the standard C++ stream input operator:
std::string line;
std::ifstream input(...);
while (std::getline(input, line))
{
std::istringstream iss(line);
int v1;
double v2;
std::string v3;
iss >> v1 >> v2;
std::getline(iss, v3);
}

Related

c++ txt to vector failure

Can't read/get text file(.txt) to vector, tried 3 approaches found on web (numbered 0-1-2). So far got number of words (distance algorithm), file size (didn't include code), but no vector. Please point me to mistake. Thank you.
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;
void intoVector (ifstream &stream, vector<string> &vector) {
string s;
getline (stream, s);
istringstream iss (s);
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(vector));
}
int main(int argc, const char * argv[]) {
string s1="text.txt";
ifstream file (s1);
if (!file) {
cout<<"Couldn't find file"<<endl; exit(1);
}else {cout<<"File is found"<<endl;}
//words count - o.k.
istream_iterator<string> start(file), end;
cout<<"Word count: "<<distance(start, end)<<endl;//iterator distance - difference beteween 2 iterators, type ptrdiff_t
if (!file.is_open()) {
cout<<"File isn't open"<<endl;
}
//0)try
vector<string> vec1;
intoVector(file, vec1);
cout<<vec1.size()<<endl; //result- 0
//1) try1
vector<string> text1(start, end);
cout<<"Vector size "<<text1.size()<<endl; //result - 1, 1st word
copy(text1.begin(), text1.end(), ostream_iterator<string>(cout, " "));
//2)try2
vector<string> vec2;
string s2;
while (getline(file, s2)) {
vec2.push_back(s2);
}
cout<<"vec size "<<vec2.size()<<endl; //Result -0
}
All approached are working when I disable ifstream_iterator (distance algorithm). Previously had to make file size calculation as a function (outside main) 'cause it was conflicting with mentioned iterator

split a set of data into different category

I have a .txt file which is a set of data (2000 lines) example shown below
Time,Price ($),Volume,Value ($),Condition
10/10/2013 04:57:27 PM,5.81,5000,29050.00,LT XT
10/10/2013 04:48:05 PM,5.81,62728,364449.68,SX XT
10/10/2013 04:10:33 PM,5.81,451,2620.31,
10/10/2013 04:10:33 PM,5.81,5000,29050.00,
How do i split them into chunks of each category? Example:
Volume - (whole data of volume)
Price - (whole data of price)
I understand that need to use delimiter to split but i don't know how to go about it (would need a little push on codings).
I'm using vectors to store these set of data by line.
Any help will be appreciated. Thanks
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<sstream>
//#include "Header.h"
using namespace std;
int main()
{
//open file
ifstream inFile("Course_of_sale.txt", ifstream::in);
// if can read
if (inFile.good())
{
std::vector<string> strVector;
//create vector
string line;
//read and push to back
while (getline(inFile, line))
{
getline(inFile, line);
strVector.push_back(line);
}
vector<string>::iterator it;
for (it = strVector.begin(); it < strVector.end(); it++)
{
cout << *it << endl;
}
stringstream ss(line);
string field;
while (getline(ss, field, ','))
{
getline(inFile, line);
strVector.push_back(line);
}
cout << "\nSize : " << strVector.capacity() << " elements \n";
}
system("Pause");
Currently only managed to do a read from file.(and this code is copied from SO)
This was my attempt.
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
struct entry {
int time;
double price;
int volume;
double value;
std::string condition;
entry(const int ti, const double pr, const int vo, const double va, const std::string &co):
time{ ti }, price{ pr }, volume{ vo }, value{ va }, condition{ co }
{ }
};
std::vector<std::string> &split(const std::string &str, const char delim, std::vector<std::string> &ret) {
std::stringstream ss(str);
std::string tmp;
while (std::getline(ss, tmp, delim))
ret.push_back(tmp);
return ret;
}
int main(int argc, char **argv) {
std::vector<entry> vec;
std::ifstream file("test.txt");
std::string line;
std::vector<std::string> str;
while (std::getline(file, line)) {
std::vector<std::string>().swap(str);
split(line, ',', str);
std::string tmp{ "" };
if (str.size() > 4)
std::string tmp(str.at(4));
entry e(
std::stoi(str.at(0)),
std::stod(str.at(1)),
std::stoi(str.at(2)),
std::stod(str.at(3)),
tmp
);
vec.push_back(e);
}
system("pause");
return 0;
}
It's only fault tolerant if you leave off the condition.

Reading and storing integers in a file

I have a file.txt such as :
15 25 32 // exactly 3 integers in the first line.
string1
string2
string3
*
*
*
*
What I want to do is, reading 15,25,32 and store them into lets say int a,b,c;
Is there anyone to help me ? Thanks in advance.
The standard idiom uses iostreams:
#include <fstream>
#include <sstream>
#include <string>
std::ifstream infile("thefile.txt");
std::string first_line;
if (!infile || !std::getline(first_line, infile)) { /* bad file, die */ }
std::istringstream iss(first_line);
int a, b, c;
if (!(iss >> a >> b >> c >> std::ws) || iss.get() != EOF)
{
// bad first line, die
}
// use a, b, c
You can use a std::ifstream to read file content:
#include <fstream>
std::ifstream infile("filename.txt");
Then you can read the line with the numbers using std::getline():
#include <sstream>
#include <string>
std::string line;
std::getline(infile, line);
Then, you can use a std::istringstream to parse the integers stored in that line:
std::istringstream iss(line);
int a;
int b;
int c;
iss >> a >> b >> c;

Initializing a vector from a text file

I am attempting to write a program which can read in a text file, and store each word in it as an entry in a string type vector. I am sure that I am doing this very wrong, but it has been so long since I have tried to do this that I have forgotten how it is done. Any help is greatly appreciated. Thanks in advance.
Code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile;
vector<string>::iterator it;
it = input.begin();
readFile.open("input.txt");
for (it; ; it++)
{
char cWord[20];
string word;
word = readFile.get(*cWord, 20, '\n');
if (!readFile.eof())
{
input.push_back(word);
}
else
break;
}
cout << "Vector Size is now %d" << input.size();
return 0;
}
One of the many possible ways is a simple:
std::vector<std::string> words;
std::ifstream file("input.txt");
std::string word;
while (file >> word) {
words.push_back(word);
}
operator >> takes care of only words divided by whitespaces (including new-lines) being read.
And in case you would be reading it by lines, you might also need to explicitly handle empty lines:
std::vector<std::string> lines;
std::ifstream file("input.txt");
std::string line;
while ( std::getline(file, line) ) {
if ( !line.empty() )
lines.push_back(line);
}
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile("input.txt");
copy(istream_iterator<string>(readFile), {}, back_inserter(input));
cout << "Vector Size is now " << input.size();
}
Or, shorter:
int main()
{
ifstream readFile("input.txt");
cout << "Vector Size is now " << vector<string>(istream_iterator<string>(readFile), {}).size();
}
I'm not going to explain, because there's about a zillion explanations on StackOverflow already :)

Write CSV file into vectors in C (continued)

Basically I have 14800x8 matrix that has been extracted from matlab as CSV file ("moves.mo"). I need to read this file into 14800 vectors with 8 values each.
Here is a few lines from the file:
1,2,3,4,-1,-3,-2,-4
1,2,3,5,-1,-3,-2,-5
1,2,3,6,-1,-3,-2,-6
1,2,3,7,-1,-3,-2,-7
1,2,3,8,-1,-3,-2,-8
1,2,3,9,-1,-3,-2,-9
I wrote the following code:
#include <iostream>
#include <fstream>
#include<stdio.h>
#include <string>
#include <istream>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
std::fstream inputfile;
inputfile.open("moves.da");
std::vector< std::vector<int> > vectorsmovesList; //declare vector list
while (inputfile) {
std::string s;
if (!getline( inputfile, s )) break;
istringstream ss( s );
vector <int> recordmove;
while (ss)
{
if (!getline( ss, s, ',' )) break;
int recordedMoveInt = atoi(s.c_str());
recordmove.push_back( recordedMoveInt );
}
vectorsmovesList.push_back( recordmove );
}
if (!inputfile.eof())
{
cerr << "Fooey!\n";
}
It compiles but does not give me desirable output (i.e. just prints Fooey!) . I don't know why... This problem at this point is driving me insane.
Please help!
There are better ways to read integers in C++. For example:
std::string s;
if (!getline( inputfile, s )) break;
istringstream ss( s );
int recordedMove;
while (ss >> recordedMove)
{
recordmove.push_back(recordedMove);
// consume the commas between integers. note if there are no
// separating commas, you will lose some integers here.
char garbage;
ss >> garbage;
}
Also, you're not printing out your result anywhere. Here's how you would do it:
vector<vector<int> >::const_iterator ii;
for (ii = vectorsmovesList.begin(); ii != vectorsmovesList.end(); ++ii)
{
vector<int>::const_iterator jj;
for (jj = ii->begin(); jj != ii->end(); ++jj)
cout << *jj << ' ';
cout << endl;
}
Obviously, you'd do that after you've parsed and closed the CSV file.