#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream fout1;
ofstream fout2;
string fnameOdd;
string fnameEven;
int x;
int numEven(0);
int numOdd(0);
cout << "Enter name of file for odd integers: ";
getline(cin, fnameOdd);
fout1.open(fnameOdd.c_str(), ios::out);
cout << "Enter name of file for even integers: ";
getline(cin, fnameEven);
fout2.open(fnameEven.c_str(), ios::out);
if(!fout1.is_open())
{
cerr << "Unable to open file" << fnameOdd << endl;
exit(10);
}
if(!fout2.is_open())
{
cerr << "Unable to open file" << fnameEven << endl;
exit(15);
}
cout << "Enter list of odd and even integers (followed by 0): " << endl;
cin >> x;
while (x != 0)
{
if (x % 2 == 0)
{
numEven++;
}
else
{
numOdd++;
}
}
fout1 << numEven;
fout2 << numOdd;
cout << "File " << fnameOdd << " contains " << numOdd << " odd integers. " <<endl;
cout << "File " << fnameEven << " contains " << numEven << " even integers. " <<endl;
fout1.close();
fout2.close();
return 0;
}
I am having trouble outputting anything to the screen, nothing is happening it is just inputting the file names and integers. i am not sure how to output what i have wrote onto the file, and reading my book does not help.
You forget that your input statement cin >> x; needs to go inside the loop as well
cin >> x;
while (x != 0)
{
if (x % 2 == 0)
{
numEven++;
}
else
{
numOdd++;
}
cin >> x; // new line here
}
The way you wrote it after you input the first value for x, it never changes it's value again. So the while loop never ends. That's why you didn't see any output.
Related
I'm relatively new to C++ so please excuse the use of namespace std. I'm trying to read a numeric value from a file, and determine its prime factors. Despite not failing it will ignore input, displaying an endless loop of '0' and '2is a prime number'. Below is both my code and text file.
Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int div = 0, num = 0, count = 0;
string inputFile;
ifstream fin;
cout << "Enter input file name: ";
getline(cin, inputFile);
fin.open(inputFile.c_str());
if (fin.fail())
{
cout << "Bad file.\n";
cin.ignore();
getchar();
exit(0);
}
fin >> num;
cout << left << setw(12) << "Number" << setw(15) << "Prime Factors\n"
<< "---------------------------\n"
<< setw(12) << num << endl;
while (!fin.eof())
{
div = 2;
count++;
cout << setw(15) << num;
if (num < 0)
cout << "Can't do negative numbers\n"
else
{
cout << div;
while (div <= num / 2)
{
if (num % div == 0)
{
num = num / div;
cout << div;
}
else
div++;
}
}
if (div >= num / 2)
cout << "is a prime number\n";
fin.ignore(10, '\n');
fin >> num;
cout << setw(12) << num << endl;
}
if (count == 0)
cout << "No data was processed, data file is empty.\n";
cin.ignore(10, '\n');
getchar();
return (0);
}
Input.txt (Ended with a singular blank line for EoF):
348
23
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 :-)
So I am trying to read from a text file. It shows that I can successfully read from the file But when I try to cout the values, it just shows 0, while I have other values in the text file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
std::ifstream file("numbers.txt");
if (file) {
cout << "Managed to read file successfully. \n";
}else{
cout << "Unable to read file.";
}
int x, y;
file >> x >> y;
cout << "Num 1: " << x << endl;
cout << "Num 2: " << y << endl;
return 0;
}
With the numbers.txt file
45
15
Your code work find with gcc.
int main()
{
std::ifstream file("numbers.txt");
if (file)
{
cout << "Managed to read file successfully. \n";
int x, y;
file >> x >> y;
cout << "Num 1: " << x << endl;
cout << "Num 2: " << y << endl;
}
else
{
cout << "Unable to read file.";
}
return 0;
}
The above code will print status of your operation,if you want to read and display contents the you have to write your code like this:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream stream1("D:\\file1.txt");
char a[80];
if(!stream1)
{
cout << "While opening a file an error is encountered" << endl;
}
else
{
cout << "File is successfully opened" << endl;
}
while(!stream1.eof())
{
stream1 >> a;
cout << a << endl;
}
return(0);
}
I am trying to figure out how to store binary data that is saved to a .dat file "customer.dat" into a structure of vectors. I thought I have had it a few times, but with no luck.
Basically, I have a working method of storing the data into the .dat file, the newEntry function, but I can not seem to work out on how to bring the data back one set at a time into an order structure of vectors. The function in question is the searchDisplay function. Here is the code:
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
const int NAME_SIZE = 51, ADDR_SIZE = 51, PHONE_SIZE = 14;
struct Client {
char name[NAME_SIZE];
char address1[ADDR_SIZE];
char address2[ADDR_SIZE];
char phone[PHONE_SIZE];
double acctBal;
double lastPay;
};
//void welcome();
int menu();
int newEntry();
int searchDisplay();
int main() {
int selection;
int option = 0;
int end;
//welcome();
while (option != 6) {
selection = menu();
if (selection == 1) {
cin.ignore();
end = newEntry();
if (end == 0) {
return 0;
}
} else if (selection == 2) {
end = searchDisplay();
if (end == 0) {
return 0;
}
}
}
return 0;
}
int menu() {
int selection;
cout << "User please enter the number that corresponds with what you wish to do..."
<< endl;
cout << "1) Add An Entry" << endl
<< "2) Search for a Specfic Person and erase." << endl;
cin >> selection;
return selection;
}
int newEntry() {
string input;
Client person;
char response = 'y';
//create file object and open file
fstream customer("customer.dat", ios::app | ios::binary);
if (!customer) {
cout << "Error opening file. Program aborting." << endl;
return 0;
}
do {
cout << "Enter person information:" << endl << endl;
cout << "Name: " << endl;
getline(cin, input);
strcpy(person.name, input.c_str());
cout << endl << person.name;
cout << endl << "Street Adress (And Apartment Number):" << endl;
cin >> person.address1;
getline(cin, input);
strcpy(person.address1, input.c_str());
cout << endl << "City, State, Zipcode: " << endl;
cin >> person.address2;
getline(cin, input);
strcpy(person.address2, input.c_str());
cout << endl << "Phone: " << endl;
cin >> person.phone;
getline(cin, input);
strcpy(person.phone, input.c_str());
cout << endl << "Account Balance: " << endl;
cin >> person.acctBal;
//input validation to ensure a non neg number
cin.ignore();
cout << endl << "Last Payment: " << endl;
cin >> person.lastPay;
//input validation to ensure a non neg number
customer.write(reinterpret_cast<char *>(&person), sizeof(person));
cout << endl << "Do you want to enter another record? (Enter Y for Yes, N for No) " << endl;
cin >> response;
cout << "_______________________________________________" << endl << endl;
if (toupper(response) == 'Y') {
cin.ignore();
}
} while (toupper(response) == 'Y');
customer.close();
return 1;
}
/********************************************
My main problem is with the below function
********************************************/
int searchDisplay() {
vector<Client> store(2);
Client foo;
int i = 0;
fstream customer("customer.dat", ios::in | ios::binary);
if (!customer) {
cout << "Error opening file. Program aborting." << endl;
return 0;
}
//MY HOPE WAS THIS WOULD STORE EACH SET OF DATA INTO THE STRUCTURE OF VECTORS
customer.read(reinterpret_cast<char *>(&store), sizeof (store[0]));
while (!customer.eof()){
cout << store[i].name << ":" << endl
<< store[i].address1 << endl
<< store[i].address2 << endl
<< store[i].phone << endl
<< store[i].acctBal << endl
<< store[i].lastPay << endl << endl;
i++;
customer.read(reinterpret_cast<char *>(&store), sizeof (store[i]));
}
customer.close();
return 1;
}
Sorry if any of the coding is a little off in its indenting, I was having issues with the method of putting the code onto the text block.
But yes, any help would be great. This is my first time working with vectors significantly and first time ever with more file classes.
Your first problem is the opening of the data file for writing. You are currently opening it with the flag "ios::app", when it should be "ios::out". Over here (gcc version 4.7.2) i get no output to file when opening the file with "ios::app".
Using "ios::out" it creates a file and dumps the data into it.
The second problem is in the line where you open and read the file. You are missing a "[0]". Check the corrected version below:
customer.read(reinterpret_cast<char *>(&store[0]), sizeof (store[0]));
Making this modifications you can get closer to the desired results.
The main problem here is that writing and reading binary files is a bit different from regular text files, that have indications of line endings, for example. You need to organize your data differently, which can be quite complicated. Try Serializing with Boost.
Sorry for the lack of previous explanation to my school's assignment. Here's what I'm working with and what I have / think I have to do.
I have the basic structure for populating the address book inside an array, however, the logic behind populating a text file is a bit beyond my knowledge. I've researched a few examples, however, the implementation is a bit tricky due to my novice programming ability.
I've gone through some code that looks relevant in regard to my requirements:
ifstream input("addressbook.txt");
ofstream out("addressbook.txt");
For ifstream, I believe implementing this into the voidAddBook::AddEntry() would work, though I've tried it and the code failed to compile, for multiple reasons.
For ostream, I'm lost and unsure as to how I can implement this correctly. I understand basic file input and output into a text file, however, this method is a bit more advanced and hence why I'm resorting to stackoverflow's guidance.
#include <iostream>
#include <string.h> //Required to use string compare
using namespace std;
class AddBook{
public:
AddBook()
{
count=0;
}
void AddEntry();
void DispAll();
void DispEntry(int i); // Displays one entry
void SearchLast();
int Menu();
struct EntryStruct
{
char FirstName[15];
char LastName[15];
char Birthday[15];
char PhoneNum[15];
char Email[15];
};
EntryStruct entries[100];
int count;
};
void AddBook::AddEntry()
{
cout << "Enter First Name: ";
cin >> entries[count].FirstName;
cout << "Enter Last Name: ";
cin >> entries[count].LastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].Birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].PhoneNum;
cout << "Enter Email: ";
cin >> entries[count].Email;
++count;
}
void AddBook::DispEntry(int i)
{
cout << "First name : " << entries[i].FirstName << endl;
cout << "Last name : " << entries[i].LastName << endl;
cout << "Date of birth : " << entries[i].Birthday << endl;
cout << "Phone number : " << entries[i].PhoneNum << endl;
cout << "Email: " << entries[i].Email << endl;
}
void AddBook::DispAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DispEntry(i);
}
void AddBook::SearchLast()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].LastName) == 0)
{
cout << "Found ";
DispEntry(i);
cout << endl;
}
}
}
AddBook AddressBook;
int Menu()
{
int num;
bool BoolQuit = false;
while(BoolQuit == false)
{
cout << "Address Book Menu" << endl;
cout << "(1) Add A New Contact" << endl;
cout << "(2) Search By Last Name" << endl;
cout << "(3) Show Complete List" << endl;
cout << "(4) Exit And Save" << endl;
cout << endl;
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
return 0;
}
int main (){
Menu();
return 0;
}
As it currently stands, I'm still stuck. Here's where I believe I should start:
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
//save first name
//save last name
//save dob
//save phone number
//save email
//exit
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
Somehow, during menu option 4 the array should dump the data into a .txt file and arrange it in a way that it can be easily imported upon reloading the program. I'm a little confused as to how I can store the array data from each character array into a .txt file.
Well first, if the input is coming from the file input, then instead of doing cin >> x you would have to do input >> x. If it's coming from standard input (the keyboard), then you can use cin.
Also, your else if statement should be something like this:
while (true)
{
// ...
else if (num == 4)
{
for (int i = 0; i < AddressBook.count; ++i)
{
AddBook::EntryStruct data = AddressBook.entries[i];
out << data.FirstName << " " << data.LastName
<< std::endl
<< data.Birthday << std::endl
<< data.PhoneNum << std::endl
<< data.Email;
}
}
break;
}