Directing output into a .txt file in C++ - 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

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;
}

Why does my try catch exception stop working after the catch?

I have a segment of code here that runs partially. I am able to input both the characters (c, a, r) and numbers initially, but after entering a character input, the code no long accepts integer inputs. Why does this happen?
I think it has something to do with my try catch exception.
code:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int item;
string input;
float total = 0;
int flag = 0;
float maintotal = 0;
int main() {
cout.precision(2);
cout << std::fixed;
cout << "Vending Machine" << endl;
cout << "----Items------" << endl;
vendingMachine();
cout << "Enter c to checkout" << endl;
cout << "Enter a to add items" << endl;
cout << "Enter r to remove items" << endl;
while (true) {
cout << "Enter your selection: " << flush;
cin >> input;
try
{
item = stoi(input); //convert to int
}
catch (exception &e)
{
//std::cout << e.what();
flag = -1; //if not set flag
if (input == "c"){
checkout();
}
if (input == "a") {
add();
cout << "mainadd total: " << total << endl;
}
if (input == "r") {
remove();
}
}
if (flag != -1) //only execute with no errors
{
total = enterSelection();
cout << "total from main: " << total << endl;
}
}
return 0;
}
Once you've set flag to -1, it's never changed back to 0. The initialization you perform at the top of the file happens just once, before main is even called. So, after that, when you set it to -1 in the catch block, it never went to a part of the code that set it back to 0. As you saw, setting flag = 0 at the beginning of the while loop corrects that omission.

Issue with C++ code

I was trying to figure out this task, but so far have been unsuccessful. I think I understand the logic behind it, I just don’t know how to nest loops so it works (if that makes sense). I would very much appreciate your help!
Task:
"Create an application in which a user enters full numbers until they enter number 0 (zero). The application should print out how many even numbers have been entered, how many odd numbers, sum of even numbers and sum of odd numbers, and total sum of numbers."
my code so far:
#include <iostream>
using namespace std;
void main() {
do {
int input1;
cout << "Type in a number";
cin >> input1;
} while (input1 != 0);
cout << "Type in a number";
cin >> input1;
if (input1 % 2 == 0)
{
int even = 0;
while (input1 % 2 == 0 )
cout << even;
even++;
}
else
{
int odd = 0;
while (odd != 0)
{
cout << odd;
odd++;
}
}
}
system("pause");
}
Note: I did not try to do the third part of the task, since the second one won't work :/ I figured out first part, and I did it with do while loop. Thanks again.
Try this:
int oddCount = 0;
int evenCount = 0;
int oddSum = 0;
int evenSum = 0;
int in;
do
{
std::cout << "Type in a number:";
std::cin >> in;
if (0 == in)
break;
if ( in % 2 == 0 )
{
evenCount++;
evenSum += in;
}
else
{
oddCount++;
oddSum += in;
}
} while ( true );
std::cout << "Odd count: " << oddCount << std::endl;
std::cout << "Even count: " << evenCount << std::endl;
std::cout << "Odd sum: " << oddSum << std::endl;
std::cout << "Even sum: " << evenSum << std::endl;
std::cout << "Total sum: " << oddSum + evenSum << std::endl;
Take a look at this piece of code:
#include <iostream>
using namespace std;
int main() {
int input;
int total_sum = 0, odd_sum = 0, even_sum = 0;
int odd_count = 0, even_count = 0;
do {
cout << "Type in a number: ";
cin >> input;
total_sum += input;
if (input % 2 == 0)
{
even_count++;
even_sum += input;
}
else
{
odd_count++;
odd_sum += input;
}
} while (input != 0);
cout << "Total Sum: " << total_sum << endl;
cout << "Even sum: " << even_sum << endl;
cout << "Odd sum: " << odd_sum << endl;
cout << "Even Count: " << even_count << endl;
cout << "Odd Count: " << odd_count << endl;
return 0;
}
See how input is declared outside of the loop. if it was inside it, then you essentially create it each time you enter the loop. that would be fine if you did not want to use its values outside of the loop (like in the loops condition).
Also, notice that the values you need to calculate can be updated within that same loop.

Why does program complain of too many commas?

Here is my code, I have attached the screenshot of what output Zybooks expects, and what my output is. I am trying to get it to output exactly what Zybooks is asking, however something seams to be wrong. It is compiling though. Or maybe Zybooks is just being stupid?
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include <cstring>
using namespace std;
int main() {
string title;
string col1;
string col2;
string val;
int numCommas = 0;
vector<string> stringData;
vector<int> intData;
cout << "Enter a title for the data:" << endl;
getline(cin, title);
cout << "You entered: " << title << endl << endl;
cout << "Enter the column 1 header:" << endl;
getline(cin, col1);
cout << "You entered: " << col1 << endl << endl;
cout << "Enter the column 2 header:" << endl;
getline(cin, col2);
cout << "You entered: " << col2 << endl << endl;
while (1) {
cout << "Enter a data point (-1 to stop input):" << endl;
getline(cin, val);
if (val == "-1") {
break;
}
if (val.find(',') == -1) {
cout << "Error: No comma in string." << endl << endl;
}
else {
for (int i = 0; i < val.length(); i++) {
if (val.at(i) == ',') {
numCommas++;
if (numCommas > 1){
break;
}
}
}
if (numCommas == 1) {
stringData.push_back(val.substr(0, val.find(',')));
intData.push_back(stoi(val.substr(val.find(',') + 1, val.length() - 1)));
cout << "Data string: " << val.substr(0, val.find(',')) << endl;
cout << "Data integer: " << stoi(val.substr(val.find(',') + 1, val.length() - 1)) << endl;
}
else {
cout << "Error: Too many commas in input." << endl << endl;
}
}
}
return 0;
}
Thanks.
Thanks.
Your problem is that you initialise numCommas to zero at the start of the program rather than at the start of each author input. That means, once it exceeds one, it will stay that high at least(a), meaning future inputs will always be seen as having too many commas.
You just need to set it to zero immediately before checking each input.
(a) Well, until it wraps around (if it wraps around). But that will be an awful lot of commas you need to input :-)

C++ program to display votes in percentage not showing correct result

I'm solving some C++ problems from ebooks. I made this C++ program but it isn't working properly. I've 2 problems:
Even after applying the forumla (votePercentage = firstAnswer/totalVotes*100;) it isn't showing the output, but only 0.
The program should display the bar chart, how am I suppose to do that? Any hints, reference or solution will be appreciated.
Here is my code:
/*
* Write a program that provides the option of tallying up the
* results of a poll with 3 possible values.
* The first input to the program is the poll question;
* the next three inputs are the possible answers.
* The first answer is indicated by 1, the second by 2, the third by 3.
* The answers are tallied until a 0 is entered.
* The program should then show the results of the poll—try making
* a bar graph that shows the results properly scaled to fit on
* your screen no matter how many results were entered.
*/
#include <iostream>
#include <string>
void startPoll (void);
void showPoll (void);
void pollCheck (void);
std::string pollQuestion, answer1, answer2, answer3;
int pollChoice, firstAnswer, secondAnswer, thirdAnswer;
int main (void)
{
int totalVotes = 1;
float votePercentage;
startPoll();
showPoll();
for(;;totalVotes++)
{
if (pollChoice == 1)
{
firstAnswer = firstAnswer + 1;
}
else if (pollChoice == 2)
{
secondAnswer++;
}
else if (pollChoice == 3)
{
thirdAnswer++;
}
else
{
std::cout << "==============*======*======*==============\n"
<< " RESULT \n"
<< "==============*======*======*==============\n"
<< "Question: " << pollQuestion << "\n"
<< "Total Votes: " << totalVotes << "\n";
votePercentage = (firstAnswer/totalVotes)*100;
std::cout << answer1 << ": " << firstAnswer << " votes. | " << votePercentage << "\n";
votePercentage = secondAnswer/totalVotes*100;
std::cout << answer2 << ": " << secondAnswer << " votes. | " << votePercentage << "\n";
votePercentage = thirdAnswer/totalVotes*100;
std::cout << answer3 << ": " << thirdAnswer << " votes. | " << votePercentage << "\n";
return 0;
}
std::cout << "\nEnter your vote again\nOR\nuse 0 to show the results.\n";
std::cin >> pollChoice;
}
std::cout << "Error: Something went wrong!\n";
}
void startPoll (void)
{
std::cout << "Enter your poll question:\n";
getline (std::cin, pollQuestion, '\n');
std::cout << "Enter answer 1:\n";
getline (std::cin, answer1, '\n');
std::cout << "Enter answer 2:\n";
getline (std::cin, answer2, '\n');
std::cout << "Enter answer 3:\n";
getline (std::cin, answer3, '\n');
}
void showPoll (void)
{
std::cout << "==============|======|======|==============\n"
<< " POLL \n"
<< "==============|======|======|==============\n"
<< pollQuestion << "\n"
<< "1. " << answer1 << "\n"
<< "2. " << answer2 << "\n"
<< "3. " << answer3 << "\n\n"
<< "Enter 1,2 or 3:\n\n";
std::cin >> pollChoice;
pollCheck();
}
void pollCheck (void)
{
if (pollChoice != 1 && pollChoice != 2 && pollChoice != 3)
{
std::cout << "Wrong choice entered! Please try again.\n\n";
return showPoll();
}
}
You need to take care that integer/integer = integer. In your case, changing
(firstAnswer/totalVotes)*100
to
(1.0*firstAnswer/totalVotes)*100
or
(firstAnswer*100.0/totalVotes)
should work. They all give a floating point result.
Well, the solution for the Bar Chart could be the following:(Not written by me) I think thats very self explaining because its really basic
void line (int n, char c)
{
// this is the loop for n
for (int i = 0; i < n; i++)
cout << c << endl;
}
Here is my solution, you can see how I made the bars work by reading the comments.
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 0;
int c = 0;
cout << "What is your favorite animal? 1 Cat, ";
cout <<"2 Dog, 3 Fish, 0 Count votes" << endl;
//Choice counter
while (true)
{
int choice;
cout << "Choice: ";
cin >> choice;
if(choice == 1)
a++;
else if(choice == 2)
b++;
else if(choice == 3)
c++;
else if(choice == 0)
break;
else
continue;
}
cout << endl << " 1: " << a << endl;
cout << " 2: " << b << endl;
cout << " 3: " << c << endl;
cout << endl << "1\t" << "2\t" << "3\t" << endl;
//Finds the max voted option
int max = 0;
if(a > b && a > c)
max = a;
else if(b > c && b > a)
max = b;
else if(c > a && c > b)
max = c;
/* If the max voted option is bigger than 10, find by how much
we have to divide to scale the graph, also making 10 bar
units the max a bar can reach before scaling the others too */
int div =2;
if(max > 10)
{
do
{
max = max/div;
if(max < 10)
break;
div++;
}while(true);
}else
div = 1;
//Sets the final number for the bars
a=a/div;
b=b/div;
c=c/div;
if(a==0)
a++;
if(b==0)
b++;
if(c==0)
c++;
//Creates the bars
while(true)
{
if(a>0)
{
cout << "[]" << "\t";
a--;
}else
cout << " ";
if(b>0)
{
cout << "[]" << "\t";
b--;
}else
cout << " ";
if(c>0)
{
cout << "[]" << "\t";
c--;
}else
cout << " ";
cout << endl;
if(a==0 && b==0 && c==0)
break;
}
}