Function reads input and runs function twice - c++

I am working on a function in a program to read an input from a user then, the function will check to see if that function exists and then runs it, but it is very buggy and the functions meant to be run, run twice.
//functions with a int and a string
std::map<std::string, std::function<void(int, string)>> functionsIS = {
{"printWordWithNumber", numberPlusWord},
};
//functions with no parameters
std::map<std::string, std::function<void()>> functionsNI = {
{"Help", userHelp},
};
void CommandCheck(std::string command){
int paramInt;
string paramString;
for (int i = 0; i < functionsIS.size(); i = i++){
if (functionsIS[command]){
std::cout << "Accessed '" << command << "' reading requirements..." << std::endl;
std::cout << "Enter paramater one (integer) : ";
std::cin >> paramInt;
std::cout << std::endl<<"Enter paramater two (string)" << std::endl;
std::cin.ignore();
std::getline(std::cin,paramString);
std::cout << "running..." << std::endl;
functionsIS[command](paramInt,paramString);
}
}
for (int i = 0; i < functionsNI.size(); i = i++){
if (functionsNI[command]){
std::cout << "Accessed '" << command << "' running..." << std::endl;
functionsNI[command]();
}
}
}
Here is version for you to run:
In source:
#include <iostream>
#include <map>
#include <windows.h>
#include <string>
#include <vector>
#include <map>
#include <functional>
#include "userFunctions.h"//header file for functions
using namespace std;
std::string input;
//functions with a int and a string
std::map<std::string, std::function<void(int, string)>> functionsIS = {
{ "printWordWithNumber", numberPlusWord },
};
//functions with no parameters
std::map<std::string, std::function<void()>> functionsNI = {
{ "Help", userHelp },
};
void CommandCheck(std::string command){
int paramInt;
string paramString;
for (int i = 0; i < functionsIS.size(); i = i++){
if (functionsIS[command]){
std::cout << "Accessed '" << command << "' reading requirements..." << std::endl;
std::cout << "Enter paramater one (integer) : ";
std::cin >> paramInt;
std::cout << std::endl << "Enter paramater two (string)" << std::endl;
std::cin.ignore();
std::getline(std::cin, paramString);
std::cout << "running..." << std::endl;
functionsIS[command](paramInt, paramString);
}
}
for (int i = 0; i < functionsNI.size(); i = i++){
if (functionsNI[command]){
std::cout << "Accessed '" << command << "' running..." << std::endl;
functionsNI[command]();
}
}
}
int main(){
do{
std::cout << "Waiting For Command..." << std::endl;
cin >> input;
CommandCheck(input);
} while (input != "end");
return 0;
}
Create a header file called "functions" and paste this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void numberPlusWord(int number, std::string word){
std::cout << word << std::endl;
std::cout << number << std::endl;
}
void userHelp(){
std::cout << "I can help!" << std::endl;
}

There are a couple of problems with your code that would cause problems. The first is that you are iterationg through the function map and if the command exists you are calling it. The problem is that you are checking for the same command on every iteration so if the map contains more than one element the command will be called for each of them. You can resolve this by removing the for loop and using the find function of the map to determine if the command exists.
The second problem is that if the command does not exist an element will be created in the map for it. The if statement below will automatically insert an element using command as the key.
if(functionsIS[command]) { /*...*/}
The following update to your code will correct the problem.
void CommandCheck(std::string command)
{
int paramInt;
string paramString;
if (functionsIS.find(command) != functionsIS.end())
{
std::cout << "Accessed '" << command << "' reading requirements..." << std::endl;
std::cout << "Enter paramater one (integer) : ";
std::cin >> paramInt;
std::cout << std::endl << "Enter paramater two (string)" << std::endl;
std::cin.ignore();
std::getline(std::cin, paramString);
std::cout << "running..." << std::endl;
functionsIS[command](paramInt, paramString);
}
else if (functionsNI.find(command) != functionsNI.end())
{
std::cout << "Accessed '" << command << "' running..." << std::endl;
functionsNI[command]();
}
}

Related

Trying to run a count so I know when the last row of data is written so I can output a ']' instead of a ','

I want my output file to look like this:
However, no matter what I try, it looks like this:
I can't get my comma condition to work for the output. I've tried to use eof, counts, etc but I'm not really sure where to go.
I've tried looking at other posts, but I either can't find one linked, or I don't actually understand it.
#include <iostream>
#include <fstream> //ofstream declared in this header file
#include <string>
#include <sstream>
#include <vector>
using namespace std;
//Creates Structure For Columns
struct InputFile
{
string Date;
string Value;
string SignalStrength;
string Voltage;
};
int main()
{
ifstream input;
string Row;
string Column;
int count = 0;
int count2 = 0;
//Stores Data From Structure As Vector
vector<InputFile> InputDataStored;
input.open("Temperature.csv");
if (input.fail())
{
cerr << "File does not exist. Exiting" << endl; //cerr is cout for errors
return 1; //This could be used as an error code
}
if (!input)
{
cerr << "File could not be opened." << endl;
}
while (getline(input, Row)) //Remove top line output from sensor data when opened in Notepad
{
getline(input, Row); // read an entire row and store it in a string variable 'line'
stringstream ss{ Row }; // used for breaking words
vector<string> Columns; // creates a temporary vector of strings
while (getline(ss, Column, ',')) // read an entire row and store it in a string variable 'column'
{
Columns.push_back(Column); // add all the data of a row to the temporary vector
count++;
}
//InputFile t{}; // convert string to struct types
InputFile t;
if (Row.empty())
continue; // if it is a blank row, ignore it
else
t.Date = Columns[1];
t.Value = Columns[2];
t.SignalStrength = Columns[4];
t.Voltage = Columns[5];
InputDataStored.push_back(t); // add all the data of the new row to a vector
count2++;
cout << t.Date << " " << t.Value << " " << t.SignalStrength << " " << t.Voltage << endl;
}
input.close();
ofstream output;
output.open("SensorData.json");
if (!output)
{
cerr << "File could not be opened." << endl;
}
int JSONcount = 0;
output << "[";
for (InputFile t : InputDataStored)
{
JSONcount++;
output << "{" << endl;
output << "\"Date\": \"" << t.Date << "\"" << endl;
output << "\"Temperature\": " << t.Value << endl;
output << "\"Signal_strength\": " << t.SignalStrength << endl;
output << "\"Voltage\": " << t.Voltage << endl;
if (count2 >= JSONcount)
output << "}]" << endl;
else
output << "}," << endl;
}
output << JSONcount << endl;
output << count << endl;
output << count2;
output.close();
}
There are multiple mistakes in your code. Try something more like this instead:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
struct InputFile
{
string Date;
string Value;
string SignalStrength;
string Voltage;
};
int main()
{
vector<InputFile> InputDataStored;
string Line, Column;
int count = 0, count2 = 0;
ifstream input("Temperature.csv");
if (!input)
{
cerr << "Input file could not be opened. Exiting" << endl;
return 1;
}
getline(input, Line); //Remove top line output from sensor data when opened in Notepad
while (getline(input, Line)) // read an entire row and store it in a string variable 'line'
{
istringstream iss{ Line };
if (Line.empty())
continue;
vector<string> Columns;
while (getline(iss, Column, ','))
{
Columns.push_back(Column);
++count;
}
InputFile t;
t.Date = Columns[1];
t.Value = Columns[2];
t.SignalStrength = Columns[4];
t.Voltage = Columns[5];
InputDataStored.push_back(t);
++count2;
cout << t.Date << " " << t.Value << " " << t.SignalStrength << " " << t.Voltage << endl;
}
input.close();
ofstream output("SensorData.json");
if (!output)
{
cerr << "Output file could not be opened. Exiting" << endl;
return 1;
}
int JSONcount = 0;
output << "[";
for (const auto &t : InputDataStored)
{
++JSONcount;
if (JSONcount > 1)
output << "," << endl;
output << "{" << endl;
output << "\"Date\": \"" << t.Date << "\"" << endl;
output << "\"Temperature\": " << t.Value << endl;
output << "\"Signal_strength\": " << t.SignalStrength << endl;
output << "\"Voltage\": " << t.Voltage << endl;
output << "}";
}
output << "]" << endl;
output << JSONcount << endl;
output << count << endl;
output << count2;
output.close();
return 0;
}

compilation error due to changing function's output data type

Forgive me if this is an obvious fix as I am very much a novice when it comes to C++.
For my assignment, we were given some starter code that simulates a command-line crypto trading platform. Originally, you would be prompted to type in commands 1 to 6 to do things like print exchange stats, make an offer, print the wallet and such. For my assignment, I've been asked to create an advisor bot that takes in string commands such as 'help' and processes this to return the appropriate output.
Naturally, since there was already a system in place to do this with integers as inputs, I tried to tweak the functions (I didn't do a lot yet) so they take string commands instead and output accordingly.
Before anything else, I would like to know why the function getUserOption and input is underlined red in the while loop of the init function, but in the actual function there are no errors:
This is the contents of the header file
#pragma once
#include <vector>
#include "OrderBookEntry.h"
#include "OrderBook.h"
#include "Wallet.h"
#include <string>
using namespace std;
class MerkelMain
{
public:
MerkelMain();
/** Call this to start the sim */
void init();
private:
void advisorBot();
void printHelp();
void printMarketStats();
void enterAsk();
void enterBid();
void printWallet();
void gotoNextTimeframe();
std::string getUserOption();
void processUserOption(string userOption);
void printCurrentTime();
std::string currentTime;
// OrderBook orderBook{"20200317.csv"};
OrderBook orderBook{"20200601.csv"};
Wallet wallet;
};
This is the cpp file
#include "MerkelMain.h"
#include <iostream>
#include <vector>
#include "OrderBookEntry.h"
#include "CSVReader.h"
#include <string>
using namespace std;
MerkelMain::MerkelMain()
{
}
void MerkelMain::init()
{
int input;
currentTime = orderBook.getEarliestTime();
wallet.insertCurrency("BTC", 10);
while(true)
{
advisorBot();
input = getUserOption();
processUserOption(input);
}
}
void MerkelMain::advisorBot()
{
std::cout << "Please enter a command, or help for a list of commands" << std::endl;
std::cout << "============== " << std::endl;
std::cout << "Current time is: " << currentTime << std::endl;
}
/*void MerkelMain::printMenu()
{
// 1 print help
std::cout << "1: Print help " << std::endl;
// 2 print exchange stats
std::cout << "2: Print exchange stats" << std::endl;
// 3 make an offer
std::cout << "3: Make an offer " << std::endl;
// 4 make a bid
std::cout << "4: Make a bid " << std::endl;
// 5 print wallet
std::cout << "5: Print wallet " << std::endl;
// 6 continue
std::cout << "6: Continue " << std::endl;
std::cout << "============== " << std::endl;
std::cout << "Current time is: " << currentTime << std::endl;
}*/
void MerkelMain::printHelp()
{
std::cout << " The available commands are help, help cmd, prod, min, max, avg, predict, time, step " << std::endl;
}
void MerkelMain::printMarketStats()
{
for (std::string const& p : orderBook.getKnownProducts())
{
std::cout << "Product: " << p << std::endl;
std::vector<OrderBookEntry> entries = orderBook.getOrders(OrderBookType::ask,
p, currentTime);
std::cout << "Asks seen: " << entries.size() << std::endl;
std::cout << "Max ask: " << OrderBook::getHighPrice(entries) << std::endl;
std::cout << "Min ask: " << OrderBook::getLowPrice(entries) << std::endl;
}
}
void MerkelMain::enterAsk()
{
std::cout << "Make an ask - enter the amount: product,price, amount, eg ETH/BTC,200,0.5" << std::endl;
std::string input;
std::getline(std::cin, input);
std::vector<std::string> tokens = CSVReader::tokenise(input, ',');
if (tokens.size() != 3)
{
std::cout << "MerkelMain::enterAsk Bad input! " << input << std::endl;
}
else {
try {
OrderBookEntry obe = CSVReader::stringsToOBE(
tokens[1],
tokens[2],
currentTime,
tokens[0],
OrderBookType::ask
);
obe.username = "simuser";
if (wallet.canFulfillOrder(obe))
{
std::cout << "Wallet looks good. " << std::endl;
orderBook.insertOrder(obe);
}
else {
std::cout << "Wallet has insufficient funds . " << std::endl;
}
}catch (const std::exception& e)
{
std::cout << " MerkelMain::enterAsk Bad input " << std::endl;
}
}
}
void MerkelMain::enterBid()
{
std::cout << "Make an bid - enter the amount: product,price, amount, eg ETH/BTC,200,0.5" << std::endl;
std::string input;
std::getline(std::cin, input);
std::vector<std::string> tokens = CSVReader::tokenise(input, ',');
if (tokens.size() != 3)
{
std::cout << "MerkelMain::enterBid Bad input! " << input << std::endl;
}
else {
try {
OrderBookEntry obe = CSVReader::stringsToOBE(
tokens[1],
tokens[2],
currentTime,
tokens[0],
OrderBookType::bid
);
obe.username = "simuser";
if (wallet.canFulfillOrder(obe))
{
std::cout << "Wallet looks good. " << std::endl;
orderBook.insertOrder(obe);
}
else {
std::cout << "Wallet has insufficient funds . " << std::endl;
}
}catch (const std::exception& e)
{
std::cout << " MerkelMain::enterBid Bad input " << std::endl;
}
}
}
void MerkelMain::printWallet()
{
std::cout << wallet.toString() << std::endl;
}
void MerkelMain::gotoNextTimeframe()
{
std::cout << "Going to next time frame. " << std::endl;
for (std::string p : orderBook.getKnownProducts())
{
std::cout << "matching " << p << std::endl;
std::vector<OrderBookEntry> sales = orderBook.matchAsksToBids(p, currentTime);
std::cout << "Sales: " << sales.size() << std::endl;
for (OrderBookEntry& sale : sales)
{
std::cout << "Sale price: " << sale.price << " amount " << sale.amount << std::endl;
if (sale.username == "simuser")
{
// update the wallet
wallet.processSale(sale);
}
}
}
currentTime = orderBook.getNextTime(currentTime);
}
std::string MerkelMain::getUserOption()
{
std::string userOption = "";
std::string line;
//std::cout << "Type in 1-6" << std::endl;
std::getline(std::cin, line);
try{
userOption = std::stoi(line);
}catch(const std::exception& e)
{
//
}
std::cout << "You chose: " << userOption << std::endl;
return userOption;
}
void printCurrentTime()
{
std::cout << "Current time is: " << currentTime << std::endl;
}
void MerkelMain::processUserOption(string userOption)
{
if (userOption == "help")
{
printHelp();
}
if (userOption == "help cmd")
{
printMarketStats();
}
if (userOption == "prod")
{
enterAsk();
}
if (userOption == "min")
{
enterBid();
}
if (userOption == "max")
{
printWallet();
}
if (userOption == "avg")
{
gotoNextTimeframe();
}
if (userOption == "predict")
{
enterAsk();
}
if (userOption == "time")
{
enterBid();
}
if (userOption == "step")
{
gotoNextTimeframe();
}
}
Your getUserOption() function returns a std::string. This means when you wrote:
input = getUserOption();
In the above statement the right hand side is of type std::string. On the other hand, the left hand side is of type int. So there is mismatch in the type of left hand side and right hand side expressions. Hence the error.
You can solve this by changing the type of variable input to std::string. So replace int input; by:
std::string input; //type changed to std::string

Search Value from JSON in C++

I want to search argv[2] value in JSON but i couldn't do this. I looked the other threads but they couldn't hep either. Because i am a newbie. So ho can I do this?
#include <iostream>
#include <fstream>
#include <json/json.h>
#include <json/value.h>
using namespace std;
// struct instead of class
struct Element {
int atomNumber;
string atomName;
string atomSymbol;
string atomType;
string atomSerie;
// void funciton instead of Book(){}
void printinfo() {
cout << "Atom Number: " << atomNumber << "\n";
cout << "Atom name: " << atomName << "\n";
cout << "Atom Symbol: " << atomSymbol << "\n";
cout << "Atom Type: " << atomType << "\n";
cout << "Atom Serie: " << atomSerie << "\n";
}
};
// Arg Count Args
// V V
int main(int argc, char* argv[]) {
Json::Value ptable;
std::ifstream ptable_file("ptable.json", std::ifstream::binary);
ptable_file >> ptable;
if (strcmp(argv[1], "-p") == 0){
};
return 0;
}

Passing std::ofstream object as argument to class method

As previous questions have been answered, the way to pass a std::ofstream object as a function argument seems to be to instead pass a reference: std::ofstream&.
Whilst this solution compiles, the resulting output is not equivalent to creating an std::ofstream object within the method then calling write().
The code below does not give the correct output:
In main.cpp:
std::ofstream file(path + "output.stubs");
stub->writeRaw(file); //stub is a pointer to an object of class Stub
file.close();
In Stub.cpp:
void Stub::writeRaw(std::ofstream& file) {
file.write((char*)this, sizeof(*this));
}
The correct output is given by both changing Stub.cpp to:
void Stub::writeRaw(void) {
std::ofstream file(path + "output.stubs");
file.write((char*)this, sizeof(*this));
file.close();
}
or writing the object to the file in main instead of calling a class method.
Any help on this behaviour would be greatly appreciated!
EDIT
Some context for the class Stub:
Stub.hpp
#pragma once
#include <iostream>
#include <ios>
#include <fstream>
#include "constants.hpp"
#include "DataTypes.hpp"
class Stub {
private:
StubHeader header;
StubIntrinsicCoordinates intrinsic;
StubPayload payload;
public:
Stub(void);
virtual ~Stub(void);
StubHeader getHeader(void);
StubIntrinsicCoordinates getIntrinsicCoordinates(void);
StubPayload getPayload(void);
void setHeader(StubHeader stub_header);
void setIntrinsicCoordinates(StubIntrinsicCoordinates stub_intrinsic);
void setPayload(StubPayload stub_payload);
void print(void);
void writeRaw(std::ofstream& file);
};
And the relevant data types are defined as follows:
struct StubHeader {
uint8_t bx;
uint8_t nonant;
};
struct StubIntrinsicCoordinates {
uint8_t strip;
uint8_t column;
int crossterm;
};
struct StubPayload {
bool valid;
int r;
int z;
int phi;
int8_t alpha;
int8_t bend;
uint8_t layer;
bool barrel;
bool module;
};
EDIT 2
The (toy) code to read the stub is as follows:
std::ifstream r(path + "output.stubs");
Stub s;
r.read((char*)&s, sizeof(s));
s.print();
Only one stub is written to the file as this was a test of functionality. The print function for the Stub class is as follows:
void Stub::print(void) {
std::cout << "----- Header -----" << '\n';
std::cout << "bx: " << std::dec << (int)header.bx << '\n';
std::cout << "nonant: " << std::dec << (int)header.nonant << '\n';
std::cout << "----- Intrinsic Coordinates -----" << '\n';
std::cout << "strip: " << std::dec << (int)intrinsic.strip << '\n';
std::cout << "column: " << std::dec << (int)intrinsic.column << '\n';
std::cout << "crossterm: " << std::dec << (int)intrinsic.crossterm << '\n';
std::cout << "----- Payload -----" << '\n';
std::cout << "valid: " << std::boolalpha << payload.valid << '\n';
std::cout << "r: " << std::dec << (int)payload.r << '\n';
std::cout << "z: " << std::dec << (int)payload.z << '\n';
std::cout << "phi: " << std::dec << (int)payload.phi << '\n';
std::cout << "alpha: " << std::dec << (int)payload.alpha << '\n';
std::cout << "bend: " << std::dec << (int)payload.bend << '\n';
std::cout << "layer: " << std::dec << (int)payload.layer << '\n';
std::cout << "barrel: " << std::boolalpha << payload.barrel << '\n';
std::cout << "module: " << std::boolalpha << payload.module << "\n\n";
}
EDIT 3
For completeness and transparency, please find below the exact code for main.cpp:
int main(int argc, char const *argv[]) {
Geometry g;
g.generateModuleLUTs();
g.generateCorrectionLUTs();
std::vector<std::array<Stub*, PAYLOAD_WIDTH> > all_stubs;
std::vector<Module> modules = g.getData();
for (int i = 0; i < LINK_NUMBER; i++) {
LinkGenerator link_gen;
LinkFormatter link_formatter(link_gen.run());
StubFormatter stub_formatter(link_formatter.run(), i);
std::array<Stub*, PAYLOAD_WIDTH> stubs = stub_formatter.run(modules);
CoordinateCorrector coordinate_corrector(stubs);
all_stubs.push_back(coordinate_corrector.run());
}
std::ofstream f(path + "output.stubs");
all_stubs[0][0]->writeRaw(f);
all_stubs[0][0]->print();
std::ifstream r(path + "output.stubs");
Stub s;
r.read((char*)&s, sizeof(s));
s.print();
return 0;
}
The bug in the code was that I was not calling file.close() before constructing the std::ifstream object to read the file again. This was the cause of the unexpected behaviour.
Writing a class to file using this seems to be valid, although it is important that you are careful and know exactly what you want to write to a file.
Thank you to everyone who commented and helped to answer this question!

Directing output into a .txt file in C++

How do I direct the output of this code into a .txt file?
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
int main() {
using std::cin;
using std::cout;
using std::endl;
int input=1;
int sum=0;
int counter=1;
while (input != 0)
{
std::cout << "Please enter the hit data: ";
std::cin >> input;
if (input == 0) // after puting in data input zero
{
break;
}
else if (input != 0)
{
sum += input;
counter++;
}
}
counter = counter - 1 ;
std::cout << "Sum of hits entered: " << sum << endl ;
std::cout << "Number of hits entered: " << counter << endl ;
if ( counter < 100 )
{
std::cout << "The hits are less than 100" ;
}
else if ( counter > 100 )
{
std::cout << "The hits are greater than 100" ;
}
else if ( counter == 100 )
{
std::cout << "The hits are equal to 100" ;
}
}
Also, instead of a user having to input data, how can I get the program to read data from another .txt file? I understand you can do this all easily in the terminal; however, I would like for the program to create the .txt file.
Also, how do I get the program to recognize certain numbers? I want it to output something like "there was twelve number -11s counted".
Use std::ifstream to read input from a file, and std::ofstream to write output to a file. For example:
#include <iostream>
#include <fstream>
int main()
{
int sum = 0;
int counter = 0;
std::ifstream in("hits.txt");
if (in.is_open())
{
while (in >> input)
{
sum += input;
++counter;
}
}
else
{
std::ofstream out("hits.txt");
int input;
do
{
std::cout << "Please enter the hit data: ";
// after putting in data, input zero
if (!(std::cin >> input) || (input == 0))
break;
out << input << " ";
sum += input;
++counter;
}
while (true);
}
std::cout << "Sum of hits entered: " << sum << endl ;
std::cout << "Number of hits entered: " << counter << endl ;
if (counter < 100)
{
std::cout << "The hits are less than 100" << std::endl;
}
else if (counter > 100)
{
std::cout << "The hits are greater than 100" << std::endl;
}
else
{
std::cout << "The hits are equal to 100" << std::endl;
}
return 0;
}
Also, how do I get the program to recognize certain numbers? I want it to output something like "there was twelve number -11s counted".
You can use std:map for that, eg:
#include <iostream>
#include <fstream>
#include <map>
int main()
{
int sum = 0;
int counter = 0;
std::map<int, int> hits; // hit counter
std::ifstream in("hits.txt");
if (in.is_open())
{
while (in >> input)
{
hits[input]++;
sum += input;
++counter;
}
}
else
{
std::ofstream out("hits.txt");
int input;
do
{
std::cout << "Please enter the hit data: ";
// after putting in data, input zero
if (!(std::cin >> input) || (input == 0))
break;
out << input << " ";
hits[input]++;
sum += input;
++counter;
}
while (true);
}
std::cout << "Sum of hits entered: " << sum << endl ;
std::cout << "Number of hits entered: " << counter << endl ;
if (counter < 100)
{
std::cout << "The hits are less than 100" << std::endl;
}
else if (counter > 100)
{
std::cout << "The hits are greater than 100" << std::endl;
}
else
{
std::cout << "The hits are equal to 100" << std::endl;
}
for (auto &p : hits)
{
if (p.second == 1)
std::cout << "there was 1 number " << p.first << " counted" << std:::endl;
else
std::cout << "there were " << p.second << " number " << p.first << "'s counted" << std:::endl;
}
/* or, if you are not using C++11 or later:
for (std::map<int, int>::iterator iter = hits.begin(); iter != hits.end(); ++iter)
{
std::map<int, int>::value_type &p = *iter;
if (p.second == 1)
std::cout << "there was 1 number " << p.first << " counted" << std:::endl;
else
std::cout << "there were " << p.second << " number " << p.first << "'s counted" << std:::endl;
}
*/
return 0;
}
Outputting data to a .txt file is easy indeed. You already included , now you need to create an object from the type std::ofstream and use it to write your text into a file. I would create a function like this (above main):
#include <iostream>
#include <fstream>
#include <string>
void outputTextToFile (std::string p_text) {
//is created under your project filepath:
std::ofstream file("nameoffile.txt", std::ios::app); //"app" = appending, instead of overwriting text
file << "Writing this to a file.\n";
file.close();
}
Afterwards you can call your function in the while loop with the string text you want, like this for example:
outputTextToFile("test Text");
Reading text from a .txt file is very similar to this, I would suggest you look up this thread: Read file line by line