Change length of dashed line to match input string length? - c++

#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int income;
int tax;
cout << "What is your full name? ";
getline(cin,name);
cout << "What is your annual income? ";
cin >> income;
if (income < 50000)
{
tax = income*0.33;
}
else { tax = income*0.38; }
cout << "\t\t\t" << name << ": Tax Report" << endl;
cout << "\t\t\t" << "-------------------------" << endl;
cout << "Income =$" << income << endl;
cout << "Tax =$" << tax << endl;
system("pause");
return 0;
}
I would like the line of hyphens to match the length of the name string regardless of its length. I am in an introductory c++ class and I am sure there is a simple way to do this. Could anyone help?

cout << "\t\t\t" << string(name.length() + 12, '-') << endl;

just put in this line, instead of your current dash line
cout << "\t\t\t" << std::string(name.length(), '-') << endl;
for further information see http://en.cppreference.com/w/cpp/string/basic_string/basic_string

You can do it the following way
#include <iostream>
#include <iomanip>
int main()
{
std::string name( "01234567890" );
std::cout << "\t\t\t" << name << ": Tax Report" << std::endl;
std::cout << "\t\t\t" << std::setfill( '-' ) << std::setw( name.size() )
<< '-' << std::endl;
return 0;
}
The program output is
01234567890: Tax Report
-----------
If you want that all preceding line would be underlined then you need tp add the size of string ": Tax Report" to the argument of std:;setw For example
#include <iostream>
#include <iomanip>
int main()
{
std::string name( "01234567890" );
std::cout << "\t\t\t" << name << ": Tax Report" << std::endl;
std::cout << "\t\t\t" << std::setfill( '-' ) << std::setw( name.size() + 12 )
<< '-' << std::endl;
return 0;
}
In this case the porgram output is
01234567890: Tax Report
-----------------------
Thus all you need is to use functions std::setfill and std::setw declared in header <iomanip>. There is no need to a create a temporary object of type std::string because it is inefficient..

You can make a string of hyphens of a certain length. Get the length by first building a string for the name line and then calling its length method. Here is an example:
std::string hyphens;
hyphens.assign(length, '-');
check out thislink for more details on using strings:
http://www.cplusplus.com/reference/string/string/

Related

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 :-)

Compilation errors when using cout

I have compilation errors to just simply output a cout message. Below is my code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
char letter = 'a';
short age = 10;
int cout = 575;
long numStars = 985632145;
float pi = 3.1;
double price = 89.65;
string season = "summer";
cout << "Letter: "<< letter << endl;
std::cout << "Age: " << age<< endl;
std::cout << "Cout: " << cout << endl;
std::cout << "Number Stars: " << numStars << endl;
std::cout << "Pi: " << pi << endl;
std::cout << "Price: " << price << endl;
std::cout << "Season: " << season;
system("pause");
return 0;
}
The errors I get are on the line:
cout << "Letter: "<< letter << endl;
I have tried reinstalling VS2015 but that didn't help.
You have a variable of type int called cout - this is not allowed given that you are using namespace std. Change this variable name to something else, and avoid the statement using namespace std.
std::cout is a "reserved type/keyword" so you cannot use it as a variable name.

My console is giving me an error?

Hello there I was wondering if you may help me with my code the g++ console says "28 37 C:\Users\paul\Documents\C++\main.cpp [Error] expected ';' before 'movie'"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int tomscore;
string movie;
int metascore;
cout << "Hello there what movie are you wondering about?" << endl;
cin >> movie;
cout << "What is the Rotten Tomato score of the movie in decimal form?"<< endl;
cin >> tomscore;
cout << "What is the metascore?" << endl;
cin >> metascore;
int average = tomscore+metascore;
int averageGOD = average/2;
cout << "The average score for" " " movie " " "was" averageGOD << endl;
}
This is an error:
cout << "The average score for" " " movie " " "was" averageGOD << endl;
You need to use << in between each item you are sending to the stream. Also it is redundant to put the spaces in their own literal:
cout << "The average score for " << movie << " was " << averageGOD << endl;
If you were trying to output quote marks then use \" within the string.

Having trouble with iomanip, columns not lining up the way I expect

finishing up a long project and the final step is to make sure my data lines up in the proper column. easy. Only I am having trouble with this and have been at it for longer than i wish to admit watching many videos and can't really grasp what the heck to do So here is a little snippet of the code that I'm having trouble with:
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
cout << "Student Grade Summary\n";
cout << "---------------------\n\n";
cout << "BIOLOGY CLASS\n\n";
cout << "Student Final Final Letter\n";
cout << "Name Exam Avg Grade\n";
cout << "----------------------------------------------------------------\n";
cout << "bill"<< " " << "joeyyyyyyy" << right << setw(23)
<< "89" << " " << "21.00" << " "
<< "43" << "\n";
cout << "Bob James" << right << setw(23)
<< "89" << " " << "21.00" << " "
<< "43" << "\n";
}
which works for the first entry but the bob james entry has the numbers all askew. I thought setw was supposed to allow you to ignore that? What am i missing?
Thanks
It doesn't work as you think. std::setw sets the width of the field only for the next insertion (i.e., it is not "sticky").
Try something like this instead:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << "Student Grade Summary\n";
cout << "---------------------\n\n";
cout << "BIOLOGY CLASS\n\n";
cout << left << setw(42) << "Student" // left is a sticky manipulator
<< setw(8) << "Final" << setw(6) << "Final"
<< "Letter" << "\n";
cout << setw(42) << "Name"
<< setw(8) << "Exam" << setw(6) << "Avg"
<< "Grade" << "\n";
cout << setw(62) << setfill('-') << "";
cout << setfill(' ') << "\n";
cout << setw(42) << "bill joeyyyyyyy"
<< setw(8) << "89" << setw(6) << "21.00"
<< "43" << "\n";
cout << setw(42) << "Bob James"
<< setw(8) << "89" << setw(6) << "21.00"
<< "43" << "\n";
}
Also related: What's the deal with setw()?
The manipulators << right << setw(23) are telling the ostream that you want
the string "89" set in the right-hand edge of a 23-character-wide field.
There is nothing to tell the ostream where you want that field to start,
however, except for the width of the strings that are output since the
last newline.
And << "bill"<< " " << "joeyyyyyyy" writes a lot more characters to the output
than << "Bob James" does, so the 23-character-wide field on the second line
starts quite a bit to the left of the same field on the first line.
Stream manipulators affect the next input/output value being streamed, and then some manipulators (including setw()) reset afterwards. So you need to set the width and alignment BEFORE you output a text string, not afterwards.
Try something more like this:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void outputStudent(const string &firstName, const string &lastName,
int finalExam, float finalAvg, int letterGrade)
{
cout << setw(40) << left << (firstName + " " + lastName) << " "
<< setw(6) << right << finalExam << " "
<< setw(6) << right << fixed << setprecision(2) << finalAvg << " "
<< setw(7) << right << letterGrade << "\n";
}
int main()
{
cout << "Student Grade Summary\n";
cout << "---------------------\n\n";
cout << "BIOLOGY CLASS\n\n";
cout << "Student Final Final Letter\n";
cout << "Name Exam Avg Grade\n";
cout << "--------------------------------------------------------------\n";
outputStudent("bill", "joeyyyyyyy", 89, 21.00, 43);
outputStudent("Bob", "James", 89, 21.00, 43);
cin.get();
return 0;
}
Output:
Student Grade Summary
---------------------
BIOLOGY CLASS
Student Final Final Letter
Name Exam Avg Grade
--------------------------------------------------------------
bill joeyyyyyyy 89 21.00 43
Bob James 89 21.00 43

Simple c++ inFile and setup

The program works my only problem is that I don't know how to line up the output. When ran using the .txt file it prints the names, boxes, and name of cookies but not aligned. Also, I have to calculate the amount due for each person and display it, but i only can figure out how to do the total. Thanks for help
#include <iomanip>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream inFile;
//Declare Variables
string firstName;
string cookieName;
int boxesSold;
int numCustomers = 0;
double amountDue;
int totalCustomers;
int totalBoxesSold = 0;
double totalAmount = 0;
cout << "Girl Scout Cookies" << endl;
cout << "Created By Aaron Roberts" << endl;
inFile.open("cookie.txt");
if(inFile)
{
cout << "Customer Number Cookie" << endl;
cout << "Name Of Boxes Name" << endl;
while(inFile >>firstName>>boxesSold>>cookieName)
{
totalBoxesSold += boxesSold;
totalAmount += boxesSold * 3.50;
cout << setprecision(2) << fixed << showpoint;
cout << setw(2) << firstName
<< right << setw(7) << boxesSold
<< setw(20) << cookieName
<< endl;
numCustomers += 1;
}
cout << "\nNumber of Customers: "<< numCustomers << endl;
cout << "Total Boxes Sold: " << totalBoxesSold << endl;
cout << "Total Amount: $" << totalAmount << endl;
inFile.close();
}
else
{
cout << "Could not open file " << endl;
}
system("pause");
return 0;
}
Given you've allocated 12 characters in the header for the "Customer Name" and "Number Of Boxes" columns, you probably want to allocate 11 characters for their data, leaving one character for a trailing space.
For clarity and maintainability, I recommend you create constants for these:
int const name_column_width = 11;
int const boxes_column_width = 11;
Then you can write:
std::cout << std::setw(name_column_width) << std::left << "Customer" << ' '
<< std::setw(boxes_column_width) << std::left << "Number" << ' '
<< "Cookie"
<< std:: endl;
std::cout << std::setw(name_column_width) << std::left << "Name" << ' '
<< std::setw(boxes_column_width) << std::left << "Of Boxes" << ' '
<< "Name"
<< std:: endl;
while (inFile >> firstName >> boxesSold >> cookieName)
{
totalBoxesSold += boxesSold;
totalAmount += boxesSold * 3.50;
std::cout << std::setw(name_column_width) << std::left << firstName << ' '
<< std::setw(boxes_column_width) << std::right << boxesSold << ' '
<< cookieName
<< std::endl;
++numCustomers;
}
Resizing these columns then becomes a simple matter of changing the constant.