Beginner C++ input behviour - c++

This program is a very simple code in my practice to learn C++. The problem is at some point it does not accept input from cin and behaves strangely.
The code and the output of the program are below.
Why does the program not consider cin at "Enter your first name please"?
# include "cmath"
# include <iostream>
using namespace std;
int main()
{
string FirstName, MiddleName, LastName;
string WelcomeMessage = "Welcome to Visual C++";
int Number_of_Steps = 5;
int LoopStart = 1, LoopEnd = 5;
int AgeYears, AgeMonths;
double Pi = 3.14;
float k = 5.366;
double Age;
char* Symbol = "k";
bool TestResult = true;
MiddleName = "Milton";
cout << "Input Your First Name and Last Name" << endl;
cin >> FirstName >> LastName;
cout << "Input your Age in Years" << endl;
cin >> AgeYears;
cout << "Imput your Age in Months " << endl;
cin >> AgeMonths;
Age = AgeYears + AgeMonths / 12;
cout << endl << "Your Name is " << FirstName << ' ' << LastName << endl;
cout << "Your Age is " << Age << endl;
cout << "The Character is " << Symbol << endl;
// Testing operators
cout << "Please Enter a floating point number \n";
int n;
cin >> n;
cout << "n==" << n
<< "\n n+1==" << n + 1
<< "\n n three times==" << 3 * n
<< "\n n twice ==" << n + n
<< "\n nsquared ==" << n*n
<< "\n half of n ==" << n / 2
<< "\n square root of n ==" << sqrt(n)
<< "\n";
// Testing string addition
cout << "Eneter your first name please" << endl;
string String1, String2, String3;
cin >> String1;
cout << "Enter your family name please" << endl;
cin >> String2;
String3 = String1 + " " + String2;
cout << "Welcome" << " " << String3 << endl;
// testing inequalities to strings
string FirstString, SecondString;
cout << "Input First String "
<< endl;
cin >> FirstString;
cout << "Input Second String "
<< endl;
cin >> SecondString;
if (FirstString == SecondString)
cout << "The two words are identical \n";
if (FirstString >= SecondString)
cout << "First word is bigger than second word \n";
if (FirstString <= SecondString)
cout << "Second word is bigger than first word \n";
}

You get a hint from the output displaying .2 as the first name (String1). The cin operation before asking for first name had 64.2 on the buffer but because you read the value into an int n it only read the integer portion 64 and left the .2 on the buffer. Changing the declaration n to float n or doing some input validation if you did want an integer should leave the buffer empty when you get to the request for first name.

Related

I don't know how to write the average grade with variables

I'm trying to automatically set the number of the given variables, for example:
char subject1[30];
char subject2[30];
char subject3[30];
float grade1;
float grade2;
float grade3;
cout << "Type in your first subject: " ;
cin >> subject1;
cout << "Type in your second subject: ";
cin >> subject2;
cout << "Type in your third subject: ";
cin >> subject3;
cout << "Type in your grade for: " << subject1 << " :";
cin >> grade1;
cout << "Type in your grade for: " << subject2 << " :";
cin >> grade2;
cout << "Type in your grade for: " << subject3 << " :";
cin >> grade3;
float sum = grade1 + grade2 + grade3;
float average = (sum / 3);
cout << "AVERAGE GRADE";
cout << "************************************" << endl;
cout << subject1 << grade1 << endl;
cout << subject2 << grade2 << endl;
cout << subject3 << grade3 << endl;
cout << "====================================" << endl;
cout << "Average: " << average << endl;
return 0;
The code that calculates it works but I was wondering as how do I put the 3 grades that user inputed. So I don't have to go edit the calculation part every time I add another subject. I'm not sure if I explained well as to what I meant but I hope you understand.
A simple solution would be to store everything in a vector (that's preferred most of the time over the char array you used) an then just loop for the amount of subjects you have.
#include <vector> // need to inlcude this to be able to use vector
#include <iostream>
const int numSubjects = 3;
std::vector<std::string> prefix{"first", "second", "third"};
std::vector<std::string> subjects(numSubjects);
std::vector<float> grades(numSubjects);
for(int i = 0; i < numSubjects; i++) {
std::cout << "Type in your " << prefix[i] << " subject: ";
std::cin >> subjects[i];
std::cout << "Type in your grade for " << subjects[i] << ": ";
std::cin >> grades[i];
}
//afterwards do the calculations
Note that I initialized the vectors with a size of numSubjects that way you can access and write to indices of the vector with the [] operator. If you don't initialize vector with a size then you can use push_back() to insert elements.

Array not initializing properly within a while loop

My issue is that I have set up an array to store totals that were calculated from values read from a file. These stored totals are then added together to find the over all average.
This issue is stemming from a 'cin' at the beginning of the program where the user inputs a number and that number is supposed to drive the program by setting how many times the program loops and how many modules are inside the array. The array does not seem to work properly no matter how much I try.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string StudentGrades;
int studentID;
double quiz1;
double quiz2;
double quiz3;
double quiz4;
int total = 0;
double choice;
ofstream outFile;
double numStud=1;
cout << "Enter student ID number, Quiz 1 Grade, Quiz 2 Grade , Quiz 3 Grade, Quiz 4 Grade" << endl;
outFile.open("StudentGrades.txt");
cout << "How many students would you like to enter?" << endl;
cin >> numStud;
for (int x = 0; x < numStud; x++)
{
cout << "Enter student ID: ";
cin >> studentID;
cout << "Enter quiz grade 1: ";
cin >> quiz1;
//cout << quiz1;
cout << "Enter quiz grade 2: ";
cin >> quiz2;
//cout << quiz2;
cout << "Enter quiz grade 3: ";
cin >> quiz3;
//cout << quiz3;
cout << "Enter quiz grade 4: ";
cin >> quiz4;
//cout << quiz4;
cout << endl;
//outFile.open("StudentGrades.txt");
if (outFile.is_open())
{
cout << "inside if/else outFile" << endl;
//outFile << "File successfully open";
outFile << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
}
else
{
cout << "Error opening file";
}
outFile.close();
/*cout << "Enter 0 for no more students. Enter 1 for more students." << endl;
cin >> choice;
if (choice == 1)
continue;
if (choice == 0)
{
outFile.close();
break;
}*/
}
ifstream inFile;
inFile.open("StudentGrades.txt");
int sTotal;
int total[numStud];
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
//cout << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
total = (quiz1 + quiz2 + quiz3 + quiz4);
sTotal = total[numStud];
double avg = total / 4;
}
system("pause");
return 0;
}
int total[numStud]; is a variable length array and is not standard in C++. If you need an array and you don't know what the size will be then you should use a std::vector. A vector can be used almost exactly as an array can. For example you could would become:
int total;
std::vector<int> studentTotal;
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
//cout << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
studentTotal.push_back(quiz1 + quiz2 + quiz3 + quiz4); // insert into the vector at the end
total += studentTotal.back(); // get last inserted element
}

Error: ld returned 1 exit status June 2015

I need help understanding the [Error] id return 1 exit status due to 2 undefined references: getGrades() and getAverage(). I was issued DEV C++ and knocked out the syntax errors with mild frustration but these "linking" errors are still giving me a hard time. This is the most recent update of the code, if anyone could help me understand these linking errors that would be great.
Compiler - Dev C++
Windows 7
Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
// Function declarations
string getStudentName();
string getWork();
int getGrades();
double getAverage();
int main()
{
string studentName, work[3];
int grades[3];
double average;
// Get the name of the student
studentName = getStudentName();
// Get the work
work[3] = getWork();
// Get the grades
grades[3] = getGrades();
// Get the average
average = getAverage();
// Dynamic spacing for grades
ostringstream ss;
int gradesLength = ss.str().length();
ss <<setprecision(0) << fixed << showpoint;
ss << grades;
cout << "\n the average for " << studentName << " is: " << average << endl;
cout << "The grades for " << studentName << " are: " << endl;
cout << setw(30) << work[0] << ": " << setw(gradesLength) << grades[0] << endl;
cout << setw(30) << work[1] << ": " << setw(gradesLength) << grades[1] << endl;
cout << setw(30) << work[2] << ": " << setw(gradesLength) << grades[2] << "\n\n\n";
cout << "You have completed the program: \n";
return 0;
}
// Student Name
string getStudentName()
{
string name;
cout << "Enter students full name: ";
getline(cin, name);
return name;
}
// Assignments
string getWork()
{
string work[3];
cout << "\nEnter the name of each assignment \n";
cout << "First assignment: ";
getline (cin, work[0]);
cout << "Second assignment: ";
getline (cin, work[1]);
cout << "Third assignment: ";
getline (cin, work[2]);
return work[3];
}
// Grades
int getGrades(string work[3])
{
int grades[3];
cout << "\nEnter the grade for " << work[0] << ": ";
cin >> grades[0];
cout << "Enter the grade for " << work[1] << ": ";
cin >> grades[1];
cout << "Enter the grade for " << work[2] << ": ";
cin >> grades[2];
return grades[3];
}
// Math
double getAverage(int grades[3])
{
double average;
average = (grades[0] + grades[1] + grades[2]) / 3.0f;
return average;
}

Use Ifstream to read multiple lines?

At the moment I am using ifstream to read multiple files, like this:
File1:
name - cost
File2:
name - cost
File3:
name - cost
I am wanting to put all the files into one big file and use ifstream to read it line by line. What would I need to do this?
Here is my code:
//Lawn
int lawnLength;
int lawnWidth;
int lawnTime = 20;
float lawnCost;
string lawnName;
ifstream lawn;
lawn.open("lawnprice.txt");
lawn >> lawnName >> lawnCost;
cout << "Length of lawn required: "; // Asks for the length
cin >> lawnLength; // Writes to variable
cout << "Width of lawn required: "; // Asks for the width
cin >> lawnWidth; // Writes to variable
int lawnArea = (lawnLength * lawnWidth); //Calculates the total area
cout << endl << "Area of lawn required is " << lawnArea << " square meters"; //Prints the total area
cout << endl << "This will cost a total of " << (lawnArea * lawnCost) << " pounds"; //Prints the total cost
cout << endl << "This will take a total of " << (lawnArea * lawnTime) << " minutes" << endl << endl; //Prints total time
int totalLawnTime = (lawnArea * lawnTime);
//Concrete Patio
int concreteLength;
int concreteWidth;
int concreteTime = 20;
float concreteCost;
string concreteName;
ifstream concrete;
concrete.open("concreteprice.txt");
concrete >> concreteName >> concreteCost;
cout << "Length of concrete required: "; // Asks for the length
cin >> concreteLength; // Writes to variable
cout << "Width of concrete required: "; // Asks for the width
cin >> concreteWidth; // Writes to variable
int concreteArea = (concreteLength * concreteWidth); //Calculates the total area
cout << endl << "Area of concrete required is " << concreteArea << " square meters"; //Prints the total area
cout << endl << "This will cost a total of " << (concreteArea * concreteCost) << " pounds"; //Prints the total cost
cout << endl << "This will take a total of " << (concreteArea * concreteTime) << " minutes" << endl << endl; //Prints total time
int totalConcreteTime = (concreteArea * concreteTime);
If everything is in 1 file, your solution will involve a loop:
std::string line;
while (std::getline(fin, line))
{
...
}
And each line should be parsed to get the data you expect:
std::istringstream iss(line);
std::string name;
float cost;
if (!(iss >> name >> cost))
{
// some error occurred, handle it
}
else
{
// do something with the valid data
}

Loop to print string backwards

Program asks user for a series of strings (their name and an 8 letter word), prints their name, the first and last three letters of the word, and then prints their word backwards. need help with the for loop to display string backwards.
#include <iostream>
int main () {
string FirstName;
string LastName;
string MiddleName;
string Names;
string string1;
int len;
int x;
cout << "Hello. What is your first name?" << endl;
cin >> FirstName;
cout << FirstName << ", what is your last name?" << endl;
cin >> LastName;
cout << "And your middle name?" << endl;
cin >> MiddleName;
Names = LastName + ", " + FirstName + ", " + MiddleName;
cout << Names << endl;
cout << "Please enter a word with 8 or more characters (no spaces): " << endl;
cin >> string1;
len = string1.length();
if (len < 8){
cout << "Error. Please enter a word with 8 or more characters and no spaces: " << endl;
cin >> string1;
}
else if (len >= 8){
cout << "The word you entered has " << string1.length() << " characters."<<endl;
cout << "The first three characters are " << string1.substr(0,3) << endl;
cout << "The last three characters are " <<string1.substr(string1.length()-3,3) << endl;
x = string1.length()-1;
for (x = string1.length()-1; x >=0; x--){
cout << "Your word backwards: " << string1[x];
}
}
return 0;
}
You were almost there:
cout << "Your word backwards: ";
for (x = string1.length()-1; x >=0; x--){
cout << string1[x];
}
This way the loop will print each character in string1 but in reverse order, and the text "Your word backwards: " only once.
If you want to be fancy:
copy(string1.rbegin(), string1.rend(), ostream_iterator<char>(cout));
Simple a way is to store a string in a temp array from backwards and then use this temp array to print reverse string.
For eg:- temp[j--]=str[i ++] ; in a loop.
But be careful before this , intialise size of array 'temp' to size of original array. in this case 'str' here.
This is probably not the answer to you question but I'd one one of these:
std::cout << "Your word backwards: "
<< std::string(string1.rbegin(), string1.rend()) << '\n';
*std::copy(string1.rbegin(), string1.rend(),
std::ostreambuf_iterator<char>(std::cout << "Your word backwards: "))++ = '\n';
std::reverse(string1.begin(), string1.end());
std::cout << "Your word backwards: " << string1 << '\n';