I have a file that looks like :
4
Sam Stone
2000
Freida Flass
100500
Tammy Flass
5000
Rich Raptor
55000
I am trying to read from it, but the first getline in the while loop always returns nothing. The int 4 gets read correctly.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>
using namespace std;
const int SIZE = 60;
struct person
{
string name;
double money;
};
int main()
{
char filename[SIZE];
string input;
char inputs [50];
int value;
int count = 0;
vector<person> Members;
ifstream inFile;
inFile.open("carinfo.txt");
if (!inFile.is_open()){ cout << "Could not open fle"; }
inFile >> value;
Members.resize(value);
while (inFile.good())
{
inFile.getline(inputs, SIZE); //getline(inFile, input, '\n');
inFile >> value;
count++;
}
cout << "Total lines = " << count;
system("pause");
return 0;
}
Consider using std::string and op>>(std::istream, person) to read the elements, this works for me
#include <string>
#include <vector>
#include <limits>
#include <fstream>
#include <iostream>
#include <iterator>
struct person
{
std::string name;
double money;
};
//read in 1 person
std::istream& operator>>(std::istream& is, person& p) {
is >> p.money;
is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(is, p.name);
return is;
}
int main() {
//open stream
std::ifstream file("fname");
//create vector, let the stream operators do the hard work
std::vector<person> v((std::istream_iterator<person>(file)),
std::istream_iterator<person>());
std::cout << "count: " << v.size();
}
http://en.cppreference.com/w/cpp/iterator/istream_iterator
Related
item,price,qty,ordno,trdno
abc,54,2,123,32
xyz,34,2,345,21
item: string (char[])
price,qty (int)
ordno (long long)
trdno (int)
Make a structure for above mentioned fields
Make a vector (array, or any other container type) to hold multiple instances of this structure
1: Read file
2: read line, split values
3: initialize above mentioned structure object
4: add this object of structure to container
5: when whole file is read.. iterate over the container and print each elements values (serialno, orderno, tradeno, price, qty, item)
I tried this and it is not working-
#include<bits/stdc++.h>
using namespace std;
struct item {
string name;
double price;
int quantity;
int order_no;
int trd_no;
};
int main()
{
int n;cin>>n;
string str, T;
ifstream read("input.txt");
while(getline(read,str))
{
cout<<str<<endl;
}
stringstream X(str); // X is an object of stringstream that references the S string
cout<<endl;
while (getline(X, T, ','))
{
cout << T << endl; // print split string
}
read.close();
return 0;
}
For the code that you are showing, you misplaced just one '}' after the first while. So the code will read in the first while-loop all lines of the file and is then empty. And, then you try to split the lines. This can of course not work.
If you move the closing bracket to in front of read.close(); then your code will work. Like this:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
struct item {
string name;
double price;
int quantity;
int order_no;
int trd_no;
};
int main()
{
int n; cin >> n;
string str, T;
ifstream read("input.txt");
while (getline(read, str))
{
cout << str << endl;
stringstream X(str); // X is an object of stringstream that references the S string
cout << endl;
while (getline(X, T, ','))
{
cout << T << endl; // print split string
}
}
read.close();
return 0;
}
Caveat: this will not work, if the source file contains the header row! You can read this and throw it away, if needed.
If we follow the instruction of your homework, line by line, and assume that the first line contains header rows, then we would do like the following.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
struct Item {
std::string name;
double price;
int quantity;
long long order_no;
int trd_no;
};
int main()
{
std::vector<Item> items;
std::string str, T;
std::ifstream read("input.txt");
// Read first line and ignore it
std::getline(read, str);
while (std::getline(read, str))
{
std::istringstream X(str);
Item tempItem;
getline(X, T, ',');
tempItem.name = T;
getline(X, T, ',');
tempItem.price = std::stod(T);
getline(X, T, ',');
tempItem.quantity = std::stoi(T);
getline(X, T, ',');
tempItem.order_no = std::stoll(T);
getline(X, T, ',');
tempItem.trd_no = std::stoi(T);
items.push_back(tempItem);
}
read.close();
for (const Item& item : items)
std::cout << item.name << ' ' << item.price << ' ' << item.quantity << ' '
<< item.order_no << ' ' << item.trd_no << '\n';
}
And, with a little bit more advanced C++, where we especially keep data and methods in a class, we could do the following:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <iterator>
// The item
struct Item {
std::string name{};
double price{};
int quantity{};
long long order_no{};
int trd_no{};
// Overwrite extraction operator for easier stream IO
friend std::istream& operator >> (std::istream& is, Item& i) {
char c;
return std::getline(is >> std::ws, i.name, ',') >> i.price >> c >> i.quantity >> c >> i.order_no >> c >> i.trd_no;
}
// Overwrite inserter for easier output
friend std::ostream& operator << (std::ostream& os, const Item& i) {
return os << "Name: " << i.name << "\tPrice: " << i.price << "\tQuantity: " << i.quantity << "\tOrder no: " << i.order_no << "\tTRD no: " << i.trd_no;
}
};
// The Container
struct Data {
std::vector<Item> items{};
// Overwrite extraction operator for easier stream IO
friend std::istream& operator >> (std::istream& is, Data& d) {
// Read header line and ignore it
std::string dummy; std::getline(is, dummy);
// Delete potential old data
d.items.clear();
// Read all new data from file
std::copy(std::istream_iterator<Item>(is), {}, std::back_inserter(d.items));
return is;
}
// Overwrite inserter for easier output
friend std::ostream& operator << (std::ostream& os, const Data& d) {
std::copy(d.items.begin(), d.items.end(), std::ostream_iterator<Item>(os, "\n"));
return os;
}
};
int main()
{
// Open file and check, if it could be opened
if (std::ifstream sourceFileStream("input.txt"); sourceFileStream) {
// Define container
Data data{};
// Read and parse complete source file and assign to data
sourceFileStream >> data;
// Show result
std::cout << data;
}
else std::cerr << "\n\nError: Could not open source file:\n\n";
}
I have a question in C++
For example, i have a csv file delimited by ; with this data
name;age;country
maria;19;portugal
joao;20;espanha
carlos;18;portugal
antonio;30;alemanha
How can i get the sum of column 2 (age) -> =87
How can i get the country that shows more times (portugal)
With this code i get a complete line, but I don't know how get the information above.
I thought convert the data in a matrix (i,j) and access the values, but I don't know how.
CODE:
#include <iostream>
#include <fstream>
#include <string>
#include <limits>
using namespace std;
std::fstream &GotoLine(std::fstream& file, unsigned int num){
file.seekg(std::ios::beg);
for(int i=0; i < num - 1; ++i){
file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
return file;
}
int main(){
using namespace std;
fstream file("teste.csv");
GotoLine(file, 2);
string line2;
file >> line2;
cout << line2;
cin.get();
return 0;
}
You should use struct to hold information together in this case, as shown below. You can use the below given program as a reference(starting point) for your future purposes/programs.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <map>
#include <functional>
#include<iterator>
struct Person
{
std::string name, country;
double age = 0;
//parameterised constructor
Person(std::string pname, std::string pcountry,double page): name(pname), country(pcountry), age(page)
{
}
};
int main()
{
std::ifstream inputFile("input.txt");
std::string line,wordAge, tempName, tempCountry;
double tempAge;
//create a vector of Person objects
std::vector<Person> myVec;
if(inputFile)
{
//read the first line and discard it
std::getline(inputFile, line);
//read line by line
while(std::getline(inputFile, tempName,';'),//read name
std::getline(inputFile, wordAge,';'),//read age
std::getline(inputFile, tempCountry,'\n'))//read country
{
std::istringstream ss(wordAge);
if(ss >> tempAge)//read age
{
myVec.emplace_back(tempName, tempCountry,tempAge);
}
}
}
else
{
std::cout<<"Input file cannot be opened"<<std::endl;
}
//lets print out all the elemnts of the vector to confirm that we read the file correctly
double sum = 0;
std::map<std::string, int> myMap;//this will be used to keep track of the count corresponding to each country
for(const Person &elem: myVec)
{
std::cout <<"Name: "<<elem.name<<" Age: "<<elem.age<<" Country: "<<elem.country<<std::endl;
sum+=elem.age;
myMap[elem.country]++;
}
std::cout<<"The sum of all ages is: "<<sum <<std::endl;
std::cout<<"The country that occurs most number of times is: "<<(std::prev(myMap.end())->first)<<" which occurred :"<<(std::prev(myMap.end())->second)<<" times"<<std::endl;
return 0;
}
The output of the above program can be seen here. The input file can also be found at the above mentioned link.
Input file: In each row, there's an entry that is a pair of ID - name - GPA. Values are tab-delimited.
20210001 Bill 3.61
20210002 Joe 3.21
20210003 Royce 4.32
20210004 Lucy 2.21
I have to rearrange this file sorted by the GPA (in decreasing order).
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() {
ifstream inputfile("input.txt");
ofstream outputfile("output.txt");
if (inputfile.fail()) {
cout << "Cannot open inputfile" << endl;
}
if (outputfile.fail()) {
cout << "Cannot open outputfile" << endl;
}
if (inputfile.is_open()) {
string line;
while (getline(inputfile, line)) {
string token;
stringstream ss(line);
while (getline(ss, token, '\t')) {
}
}
}
inputfile.close();
outputfile.close();
return 0;
}
I'm not sure what to do next.
When doing I/O from/to streams (like file streams) it usually makes it easier to create a class to keep the data for each record in the file and to create overloads for operator>> (in) and operator<< (out).
Example:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
// one line in the file could possibly have this representation in your program:
struct record {
std::uint32_t ID;
std::string name;
double GPA;
};
// an overload to read one line of data from an istream (like an ifstream) using getline
std::istream& operator>>(std::istream& is, record& r) {
if(std::string line; std::getline(is, line)) {
std::istringstream iss(line);
if(not (iss >> r.ID >> r.name>> r.GPA)) {
is.setstate(std::ios::failbit);
}
}
return is;
}
// an overload to write one line to an ostream (like an ofstream)
std::ostream& operator<<(std::ostream& os, const record& r) {
return os << r.ID<< '\t' << r.name << '\t' << r.GPA << '\n';
}
With that boilerplate in place, making the actual program becomes easy.
int main() {
std::ifstream inputfile("input.txt");
// read all records from the file into a vector
std::vector<record> records(
std::istream_iterator<record>(inputfile),
std::istream_iterator<record>{}
);
// sort the records according to GPA
// if you want a decending order, just make it return rhs.GPA < lhs.GPA;
std::sort(records.begin(), records.end(),
[](const record& lhs, const record& rhs) {
return lhs.GPA < rhs.GPA;
}
);
std::ofstream outputfile("output.txt");
// put the result in the output file
std::copy(records.begin(),
records.end(),
std::ostream_iterator<record>(outputfile));
}
There may be a few things in this answer that you haven't seen before. I'll list resources for those I anticipate may require some reading:
operator<< / operator>> overloading. See Stream extraction and insertion
std::istringstream - You put a std::string in it - and then it behaves like any other std::istream (like a std::ifstream).
std::istream_iterator/std::ostream_iterator
std::sort / std::copy are two of the many algorithms in the standard library.
std::vector - A class template acting as a dynamic array where you can add and remove data, like record in this answer.
Lambda expressions - In this answer it's the functor [](const record& lhs, const record& rhs) { ... } used to sort the records.
If you know exactly how many tokens are in a line:
You could simply getline() 3 times with the tab delimiter, and store the values separately.
string id;
string name;
string gpa;
getline(ss, id, '\t');
getline(ss, name, '\t');
getline(ss, gpa, '\t');
This logic would live within your loop that iterates over the lines in the file.
You could use a struct to contain all your fields:
struct user
{
int id; string name; double point;
};
Then insert all of them into a std::vector and finally use sort() with the comp parameter to sort by points.
Code:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
struct user
{
int id; string name; double point;
};
vector<user> users;
void stripInfoFromString(string inp)
{
stringstream cur(inp);
user curUser;
cur >> curUser.id >> curUser.name >> curUser.point;
users.push_back(curUser);
}
bool compareUser(user x, user y)
{
return x.point < y.point;
}
int main()
{
string a1 = "20210001 Bill 3.61";
string a2 = "20210002 Joe 3.21";
string a3 = "20210003 Royce 4.32";
string a4 = "20210004 Lucy 2.21";
stripInfoFromString(a1);
stripInfoFromString(a2);
stripInfoFromString(a3);
stripInfoFromString(a4);
sort(users.begin(), users.end(), compareUser);
cout << fixed << setprecision(2);
for (user cur : users)
{
cout << cur.id << " " << cur.name << " " << cur.point << "\n";
}
}
Output:
20210004 Lucy 2.21
20210002 Joe 3.21
20210001 Bill 3.61
20210003 Royce 4.32
I used standard input/output to minimize the code, you can simply switch for file inputs easily.
More info:
struct : https://en.cppreference.com/w/c/language/struct
sort() : https://en.cppreference.com/w/cpp/algorithm/sort
Also, see here why is using namespace std; considered bad practice.
I would suggest defining a struct to hold the 3 tokens, and then create a std::vector holding instances of that struct for each line. You can then sort that vector on the 3rd token. You already have <vector> in your header includes.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct entry
{
int id;
string name;
double gpa;
};
int main() {
ifstream inputfile("input.txt");
ofstream outputfile("output.txt");
vector<entry> entries;
if (inputfile.fail()) {
cout << "Cannot open inputfile" << endl;
}
if (outputfile.fail()) {
cout << "Cannot open outputfile" << endl;
}
string line;
while (getline(inputfile, line)) {
istringstream iss(line);
entry e;
string token;
getline(iss, token, '\t');
e.id = stoi(token);
getline(iss, e.name, '\t');
getline(iss, token, '\t');
e.gpa = stod(token);
/* alternatively:
iss >> e.id >> e.name >> e.gpa;
*/
entries.push_back(e);
}
inputfile.close();
outputfile.close();
sort(entries.begin(), entries.end(),
[](const entry &e1, const entry &e2){
return e1.gpa > e2.gpa;
}
);
for (const entry &e : entries) {
outputfile << e.id << '\t' << e.name << '\t' << e.gpa << '\n';
}
return 0;
}
Demo
I want to read from a file two things, the full name (first name and last name)
and age. After that I want to store them in an array then print the data.
However, when I try to reading the first record is read find, but the other two are not.
Please tell me what am I missing.
Thank you.
The content of the file is:
sampleFirst1 sampleLast1
30
sampleFirst2 sampleLast2
25
sampleFirst3 sampleLast3
40
The Output is:
Name: sampleFirst1 Age: 30
Name: Age: 30
Name: Age: 30
Here's my Code:
#include "Person.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile("data.txt", ios::in);
string full_name;
int age = 0;
int i = 0;
Person personArray[3];
while (i < 3)
{
getline(inputFile, full_name);
personArray[i].set_name(full_name);
inputFile >> age;
personArray[i].set_age(age);
++i;
}
inputFile.close();
printData(personArray, 3);
cout << endl;
return 0;
}
You should not mix getline and the >> operator in that way. Prefer a simpler code like this one :
#include <iostream>
#include <fstream>
#include <array>
#include <string>
using namespace std;
struct Person {
std::string name;
int age;
void set_name(std::string const& i_name) { name = i_name; }
void set_age(int i_age) { age = i_age; }
};
int main()
{
ifstream inputFile("data.txt", ios::in);
std::string first;
std::string last;
int age = 0;
int i = 0;
std::array<Person,3> personArray;
while (i < personArray.size()) {
inputFile >> first >> last >> age;
personArray[i].set_name(first + " " + last);
personArray[i].set_age(age);
++i;
}
inputFile.close();
for(Person const& person : personArray) {
std::cout << "Name: " << person.name << " Age: " << person.age << "\n";
}
std::cout << std::flush;
return 0;
}
Or use only getline and a istringstream to pase the age if you dont want to pay the string concatenation extra cost for the full name.
A lot could be said of the parsing method but that is not the point here.
I just want to read a text file and store the data into a vector. Thereby the value weight should be sum till the limit is reached. The first four lines will be read correctly but the following will not read. What is the mistake?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
/*
Data.txt
John
6543
23
Max
342
2
A Team
5645
23
*/
struct entry
{
// passengers data
std::string name;
int weight; // kg
std::string group_code;
};
void reservations()
{
std::ofstream file;
file.clear();
file.open("reservations.txt");
file.close();
}
entry read_passenger(std::ifstream &stream_in)
{
entry passenger;
if (stream_in)
{
std::getline(stream_in, passenger.name);
stream_in >> passenger.weight;
std::getline(stream_in, passenger.group_code);
stream_in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return passenger;
}
return passenger;
}
int main(void)
{
std::ifstream stream_in("data.txt");
std::vector<entry> v; // contains the passengers data
const int limit_total_weight = 10000; // kg
int total_weight = 0; // kg
entry current;
while (!stream_in.eof())
{
current = read_passenger(stream_in);
total_weight = total_weight + current.weight;
std::cout << current.name << std::endl;
if (total_weight >= limit_total_weight)
{
break;
}
}
return 0;
}
These two lines,
std::getline(stream_in, passenger.group_code);
stream_in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
should be in the opposite order:
stream_in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(stream_in, passenger.group_code);
Think about what the purpose of the ignore is.
Also, instead of checking only for EOF, check for general error.
I.e., instead of
while (!stream_in.eof())
write
while (stream_in)
Maybe there's more wrong, but the above is what I saw immediately.
Cheers & hth.,
I try not to mix formatted and line-oriented input for precisely this reason. If it were me, and I had to use getline anywhere, I would use getline everywhere:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
#include <sstream>
struct entry
{
// passengers data
std::string name;
int weight; // kg
std::string group_code;
};
void reservations()
{
std::ofstream file;
file.clear();
file.open("reservations.txt");
file.close();
}
std::istream& operator>>(std::istream& stream_in, entry& passenger)
{
std::getline(stream_in, passenger.name);
std::string weightString;
std::getline(stream_in, weightString);
std::istringstream (weightString) >> passenger.weight;
std::getline(stream_in, passenger.group_code);
return stream_in;
}
void read_blankline(std::istream& stream_in) {
std::string blank;
std::getline(stream_in, blank);
}
int main(void)
{
std::ifstream stream_in("data.txt");
std::vector<entry> v; // contains the passengers data
const int limit_total_weight = 10000; // kg
int total_weight = 0; // kg
entry current;
while (stream_in >> current)
{
total_weight = total_weight + current.weight;
std::cout << current.name << std::endl;
if (total_weight >= limit_total_weight)
{
break;
}
read_blankline(stream_in);
}
return 0;
}