I have a question in this code. What does fucntion receive when we use cin as a argument.
For example cin stops when he finds a white space or '\n', so if the input is "1 2 3 4 5" the program will return 5 but I can't understand why.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
double max_value(istream& in) // can be called with 'infile' or 'cin'
{
double highest;
double next;
if (in >> next)
highest = next;
else
return 0;
while (in >> next)
{
if (next > highest)
highest = next;
}
return highest;
}
int main()
{
double max;
string input; cout << "Do you want to read from a file? (y/n) ";
cin >> input;
if (input == "y")
{
string filename;
cout << "Please enter the data file name: ";
cin >> filename;
ifstream infile; infile.open(filename);
if (infile.fail())
{
cerr << "Error opening " << filename << "\n";
return 1;
}
max = max_value(infile);
infile.close();
}
else
{
cout << "Insert the numbers. End with CTRL-Z." << endl; max = max_value(cin);
}
cout << "The maximum value is " << max << "\n";
return 0;
}
Related
I'm practicing ifstream usage. I want the user to enter the file they want to read, in this example num1.txt specifically. I want the console to read one letter from num1.txt and output it on its own line.
I've ran the code below, and after entering "num1.txt" into the console, I get nothing back. I've tried moving around cout << num << endl; to the inner do statement, but it ends up repeating the number 10 an infinite amount.
What am I doing wrong here?
Contents in num1.txt:
2 4 6 8 10
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string fileName, cont;
ifstream inputFile;
do {
int num = 0;
int total = 0;
cout << "Please enter the file name: ";
cin >> fileName;
inputFile.open(fileName);
if (inputFile.is_open()) {
do {
inputFile >> num;
total += num;
}
while(num > 0);
if (total != 0) {
cout << num << endl;
cout << "Total is: " << total << endl;
}
}
else {
cout << "Failed to open file." << endl;
}
inputFile.close();
cout << "Do you want to continue processing files? (yes or no): " << endl;
cin >> cont;
}
while (cont == "yes");
}
Your inner do loop is not correctly validating that operator>> is actually successful before using num. It should be looking at the stream's error state after each read. The easiest way to do that is to change your do loop into a while loop that uses the result of the read as its loop condition, eg:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string fileName, cont;
ifstream inputFile;
do {
cout << "Please enter the file name: ";
cin >> fileName;
inputFile.open(fileName);
if (inputFile.is_open()) {
int num = 0;
int total = 0;
while (inputFile >> num) {
total += num;
}
inputFile.close();
cout << "Total is: " << total << endl;
}
else {
cout << "Failed to open file." << endl;
}
cout << "Do you want to continue processing files? (yes or no): " << endl;
}
while ((cin >> cont) && (cont == "yes"));
return 0;
}
I wrote a little c++ class that read a ASCII files each line can have
4 element (int, string, int, float)
1000 I 100 10.0
or 3 (int, string, int)
1001 E 100
which means that if the string is an I the fourth element exist, not otherwise.
I am trying to write a class to insert rows.
The code asks the user to insert the object properties and then writes to file
I want to add a check
if the string is "I" then should ask to insert the float otherwise leave empty.
#include <iostream>
#include <fstream>
using namespace std;
void writing();
void deleting();
void searching();
class orderbook
{
string text;
private:
double Price = (double) NULL;
public:
int Timestamp = 0;
string Operation;
long int Id;
orderbook(){};
orderbook(const string& name)
{
ifstream infile;
infile.open(name);
if(!infile.good())
{
cout << "File is not open";
}
else
{
string line;
while(getline(infile,line))
text = text + line + '\n';
}
};
string contetns()
{
return text;
};
void SetPrice(double x = NULL)
{
Price = x;
}
float GetPrice()
{
return Price;
}
void insert(const string& name)
{
long int Id;
double Price;
float a;
orderbook ob;
cout << "Please enter Timestamp : ";
cin >> ob.Timestamp;
cout << "Please enter the Operation type: ";
cin >> ob.Operation;
cout << "Please enter Id : ";
cin >> ob.Id;
if (ob.Operation == 'I')
{
cout << "Pleae enter the Price of order: ";
cin >> a;
ob.SetPrice(a);
}
else{
ob.SetPrice()
}
ofstream myfile;
myfile.open(name, ios::app | ios::out);
myfile << ob.Timestamp << "\t";
myfile << ob.Operation << "\t";
myfile << ob.Id << "\t";
// if (ob.GetType().GetProperty("Price") != null )
// {
// myfile << ob.GetPrice() << endl;
// }
// else
// {
// myfile << endl;
// }
myfile.close();
}
void deleting()
{
string line, record;
cout << "Please Enter the name of record you want to delete: ";
cin >> record;
ifstream myfile;
ofstream temp;
myfile.open("record.txt");
temp.open("temp.txt");
while (getline(myfile, line))
{
if (line.substr(0, record.size()) != record)
temp << line << endl;
}
cout << "The record with the name " << record << " has been deleted if it exsisted" << endl;
myfile.close();
temp.close();
remove("record.txt");
rename("temp.txt", "record.txt");
}
};
int main()
{
string filename;
cout<<"Please enter the full name of the data file: ";
cin>>filename;
orderbook ob(filename);
cout << "content: " << endl << ob.contetns() << endl;
ob.insert(filename);
cout << "content: " << endl << ob.contetns() << endl;
ob.deleting();
cout << "content: " << endl << ob.contetns() << endl;
}
I get this error
class_student.cpp:64:20: error: invalid operands to binary expression
('string'
(aka 'basic_string, allocator >') and 'int') if (ob.Operation == 'I')
I have got an assignment project to make a program using C++ which maintains a list of Students (their name, age, and GPA) in a text file. The program has the following functionality:
Insertion of record
Deletion of record
Searching of record
Updating a record
When deleting a record my code takes a string name as input and removes it from the text file. However the next two lines in the file (age & gpa for that student) are left. How do I remove those too?
Following is the code for my program.
#include <iostream>
#include <fstream>
using namespace std;
void writing();
void deleting();
void searching();
class student {
public:
int age = 0;
string name;
void SetGpa(float x)
{
gpa = x;
}
float GetGpa()
{
return gpa;
}
private:
float gpa = 0.0;
};
int main()
{
int opt;
cout << "Please Enter an option number to continue:\n ";
cout << "\nPress 1 for New Record insertion";
cout << "\nPress 2 for Record Deletion";
cout << "\nPress 3 for Searching a Record";
cout << "\nPress 4 for Updating a Record";
cout << "\nEnter option Number: ";
cin >> opt;
switch (opt)
{
case 1:
{
writing();
break;
}
case 2:
{
deleting();
break;
}
case 3:
{
searching();
break;
}
case 4:
{
deleting();
writing();
cout << "Record has been updated! ";
break;
}
}
}
void writing()
{
float a;
student moiz;
cout << "Please enter name of student: ";
cin >> moiz.name;
cout << "Please enter the age of student: ";
cin >> moiz.age;
cout << "Pleae enter the Gpa of student: ";
cin >> a;
moiz.SetGpa(a);
ofstream myfile;
myfile.open("record.txt", ios::app | ios::out);
myfile << endl << moiz.name << endl;
myfile << moiz.age << endl;
myfile << moiz.GetGpa();
myfile.close();
}
void deleting()
{
string line, name;
cout << "Please Enter the name of record you want to delete: ";
cin >> name;
ifstream myfile;
ofstream temp;
myfile.open("record.txt");
temp.open("temp.txt");
while (getline(myfile, line))
{
if (line != name)
temp << line << endl;
}
cout << "The record with the name " << name << " has been deleted if it exsisted" << endl;
myfile.close();
temp.close();
remove("record.txt");
rename("temp.txt", "record.txt");
}
void searching()
{
ifstream fileInput;
fileInput.open("record.txt");
string line, search;
cout << "Please enter the term to search: ";
cin >> search;
for (unsigned int curLine = 0; getline(fileInput, line); curLine++)
{
if (line.find(search) != string::npos)
{
cout << "found: " << search << " on line: " << curLine << endl;
}
else
{
cout << "Error! Not found on Line" << curLine << endl;
}
}
}
You can add an else clause to your statement checking the name, and introduce a counter of how many of the following lines should be skipped after name was found:
int skip = 0;
while (getline(myfile, line)) {
if ((line != name) && !(skip > 0)) {
temp << line << endl;
}
else {
if(skip == 0) {
skip = 2; // Skip the next two lines also
}
else {
--skip;
}
}
}
In case of an invalid input, I want extract the invalid input from cin and store it in a variable that fits. How can I do that?
#include<iostream>
using namespace std;
int main(){
int number;
cout << "Enter a number: " << endl;
cin >> number;
if(cin.fail()){
cout << "Error!" << endl;
//HOW CAN I STORE THE INVALID INPUT WHICH IS STORED IN cin INTO A STRING?
}
return 0;
}
When you detect that failbit is set, reset it, and use std::getline to read entire line of invalid input into std::string from std::cin:
#include <iostream>
#include <string>
int main()
{
int number;
while(true)
{
std::cout << "Enter a number (0 to exit): " << std::endl;
std::cin >> number;
if(std::cin.fail())
{
std::string error_data;
std::cin.clear(std::cin.rdstate() & ~std::ios::failbit);
std::getline(std::cin, error_data);
std::cout << "You didn't enter a number - you've entered: " << error_data << std::endl;
}
else
{
std::cout << "Number is: " << number << std::endl;
if(number == 0)
{
break;
}
}
}
return 0;
}
So I have this do-while loop which is supposed to repeat asking if you want to enter info for a student if you do press y and enter info via an input() function the data is then stored in a vector. If you press q, the program is supposed to print the info contained in the vector and exit the loop.
For some reason the loop fully executes for the first and second student you enter. Then instead of repeating the loop asking if you want to enter a third student it seems to just execute the input() function. It doesn't ask you 'Enter y to continue or q to quit' and any student info you enter here does not seemed to be stored. It does this intermittently changing between executing the full loop and just the input() function. I'm wondering if anyone knows why this is happening and what I can do to fix it.
Cheers
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
using namespace std;
const int NO_OF_TEST = 4;
struct studentType
{
string studentID;
string firstName;
string lastName;
string subjectName;
string courseGrade;
int arrayMarks[4];
double avgMarks;
};
studentType input();
double calculate_avg(int marks[],int NO_OF_TEST); // returns the average mark
string calculate_grade (double avgMark); // returns the grade
void main()
{
unsigned int n=0; // no. of student
vector<studentType> vec; // vector to store student info
studentType s;
char response;
do
{
cout << "\nEnter y to continue or q to quit... ";
cin >> response;
if (response == 'y')
{
n++;
for(size_t i=0; i<n; ++i)
{
s = input();
vec.push_back(s);
}
}
else if (response == 'q')
{
for (unsigned int y=0; y<n; y++)
{
cout << "\nFirst name: " << vec[y].firstName;
cout << "\nLast name: " << vec[y].lastName;
cout << "\nStudent ID: " << vec[y].studentID;
cout << "\nSubject name: " << vec[y].subjectName;
cout << "\nAverage mark: " << vec[y].avgMarks;
cout << "\nCourse grade: " << vec[y].courseGrade << endl << endl;
}
}
}
while(response!='q');
}
studentType input()
{
studentType newStudent;
cout << "\nPlease enter student information:\n";
cout << "\nFirst Name: ";
cin >> newStudent.firstName;
cout << "\nLast Name: ";
cin >> newStudent.lastName;
cout << "\nStudent ID: ";
cin >> newStudent.studentID;
cout << "\nSubject Name: ";
cin >> newStudent.subjectName;
for (int x=0; x<NO_OF_TEST; x++)
{ cout << "\nTest " << x+1 << " mark: ";
cin >> newStudent.arrayMarks[x];
}
newStudent.avgMarks = calculate_avg(newStudent.arrayMarks,NO_OF_TEST );
newStudent.courseGrade = calculate_grade (newStudent.avgMarks);
return newStudent;
}
double calculate_avg(int marks[], int NO_OF_TEST)
{
double sum=0;
for( int i=0; i<NO_OF_TEST; i++)
{
sum = sum+ marks[i];
}
return sum/NO_OF_TEST;
}
string calculate_grade (double avgMark)
{
string grade= "";
if (avgMark<50)
{
grade = "Fail";
}
else if (avgMark<65)
{
grade = "Pass";
}
else if (avgMark<75)
{
grade = "Credit";
}
else if (avgMark<85)
{
grade = "Distinction";
}
else
{
grade = "High Distinction";
}
return grade;
}
I think this code does it:
n++;
for(size_t i=0; i<n; ++i)
{
s = input();
vec.push_back(s);
}
It asks you for two students the second time, for three student the third time, etc.
So, make it
vec.push_back(input());