I've tried to write a simple database program. The problem is that ofstream does NOT want to make a new file.
Here's an extract from the offending code.
void newd()
{
string name, extension, location, fname;
cout << "Input the filename for the new database (no extension, and no backslashes)." << endl << "> ";
getline(cin, name);
cout << endl << "The extension (no dot). If no extension is added, the default is .cla ." << endl << "> ";
getline(cin, extension);
cout << endl << "The full directory (double backslashes). Enter q to quit." << endl << "Also, just fyi, this will overwrite any files that are already there." << endl << "> ";
getline(cin, location);
cout << endl;
if (extension == "")
{
extension = "cla";
}
if (location == "q")
{
}
else
{
fname = location + name + "." + extension;
cout << fname << endl;
ofstream writeDB(fname);
int n = 1; //setting a throwaway inteher
string tmpField, tmpEntry; //temp variable for newest field, entry
for(;;)
{
cout << "Input the name of the " << n << "th field. If you don't want any more, press enter." << endl;
getline(cin, tmpField);
if (tmpField == "")
{
break;
}
n++;
writeDB << tmpField << ": |";
int j = 1; //another one
for (;;)
{
cout << "Enter the name of the " << j++ << "th entry for " << tmpField << "." << endl << "If you don't want any more, press enter." << endl;
getline(cin, tmpEntry);
if (tmpEntry == "")
{
break;
}
writeDB << " " << tmpEntry << " |";
}
writeDB << "¬";
}
cout << "Finished writing database. If you want to edit it, open it." << endl;
}
}
EDIT: OK, just tried
#include <fstream>
using namespace std;
int main()
{
ofstream writeDB ("C:\\test.cla");
writeDB << "test";
writeDB.close();
return 0;
}
and that didn't work, so it is access permission problems.
ofstream writeDB(fname); //-> replace fname with fname.c_str()
If you lookup the documentation of the ofstream constructor, you will see something like:
explicit ofstream ( const char * filename, ios_base::openmode mode = ios_base::out );
The second argument is optional, but the first one is a const char*, and not a string. To solve this problem the most simple way is to convert your string to something called a C-string (char*, which is basically an array of chars); to do that just use c_str() (it«s part of the library).
Other than that, you could just place the information directly on a C-str, and then pass it normally to the ofstream constructor.
Related
I'm trying to read in the database down below into a vector of strings while removing the header lines (lines with >db) and imputing each sequence below it into a string.
This is the code I have right now:
void read_in_database_file(string db_file) {
ifstream fin;
fin.open(db_file);
if (!fin.is_open())
{//if
cerr << "Error did not open file" << endl;
exit(1);
}//if
vector<string> database;
string line = "";
while(getline(fin, line, '>'))
{
database.push_back(line);
}
finding_kmers(database);
}
int main() {
cout << "\n" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "------------------------------------ BLAST -----------------------------------" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << endl;
cout << "Welcome to BLAST" << endl;
cout << "Please enter the name of your datafile" << endl;
string db_file = "";
getline(cin, db_file);
cout << endl;
read_in_database_file(db_file);
}
Currently, all it does is simply remove the ">" but print that line and everything else as is. How do i solve this?
database file:
>db_1
GATCTTGCATTTAGAAAATCATAAGAAATTTACTAAAAAGTATTAGGACTCATGAACAAATTTAAGAATG
TAACACTATATAAGATTGGTATACAAAAATAACTGTACTTCTTCACCAAGAAATCAAGAATCCAAAAATG
>db_2
TAGTTTGTTCTAGGATTTATGTGTTTCCTTAAAGTCTTAGTTTGATTATGTTACATTTAGCATGAGTGAC
TCCATTTTGGTTTGGTTTGGTCTGTTGGGACCTATTGCATGAGTTTAGTTCAAAACAATGGCCTCCCATA
>db_3
TTGTCCTTGCGATAGTTTACTGAGAATGATGATTTCCAATTTCATCCATATCCCTACAAAGGACATGAAC
TCATCATTTTTTATGGCTGCATAGTATTCCATGGTGTATATGTGCCATAATTTCTCAATCCAGTCTATCG
I got these questions that I stuck for the past week, "tag always starts with '<' and ends with '>'link always starts with "<a" or "<A" and ends with '>'comment always starts with "<!--" and ends with "- ->",
How can I count these using only while loop or other loops? I'm in the intro programming class, anything beyond loop, if and switch statement is not allowed to use.
Here is the program I done so far and I can't count the the lines and links at the same time, but if I break them apart, I can get the result I want.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
char ch,
prevchar,
currchar;
int linenum = 0,
tagnum = 0,
commentnum = 0,
linknum = 0,
cfilenum = 0,
ctagnum = 0;
double percent;
string line;
string filename;
cout << "========================================\n";
cout << " HTML File Analyzer\n";
cout << "========================================\n\n";
cout << "Please enter the the file name(no blank): \n";
cin >> filename;
inFile.open(filename.c_str());
while (!inFile)
{
cout << "Please re-enter the file name:\n";
cin >> filename;
inFile.open(filename.c_str());
}
cout << "========================================\n";
cout << " Text of the file \n";
cout << "========================================\n\n";
while (inFile)
{
for (linenum = 0; getline(inFile, line); linenum++);
}
inFile.get(prevchar);
inFile.get(currchar);
while (inFile)
{
if ((prevchar == '<') && (currchar == 'a'))
linknum++;
prevchar = currchar;
inFile.get(currchar);
}
cout << "========================================\n";
cout << " End of the text \n";
cout << "========================================\n\n";
cout << "Analysis of file\n";
cout << "----------------\n\n";
cout << "Number of lines: " << linenum << endl;
cout << "Number of tags: " << tagnum << endl;
cout << "Number of comments: " << commentnum << endl;
cout << "Number of links: " << linknum << endl;
cout << "Number of chars in file: " << cfilenum << endl;
cout << "Number of chars in tags: " << ctagnum << endl;
cout << "Percentage of characters in tags: " << percent << endl;
return 0;
}
After the first loop has finished, your inFile stream is pointing to the end of the file and its eof flag is set.
Issue these statements inbetween your loops to resp. clear the flag and go back to the start of the file:
inFile.clear();
inFile.seekg(0);
That the first statement is not necessary in C++11, but I don't know what environment you are using. Also note that you can do some of the counting operations together in a loop.
I'm new to c++ (and coding in general) and have recently been working with a struct held inside a vector, in this case :
struct Contact{
string name;
string address;
string phone;
string email;};
vector<Contact> contacts;
So, one of my functions involves searching through each of the contacts to find the one for which the string stored in name matches a search input. To do this I made a for loop as such:
for(int i = 0; i < contacts.size(); i++){
if(contacts[i].name == searchInput){
cout << contacts[i].address << "\n\r" << contacts[i].phone << "\n\r" << contacts[i].email;
But for some reason this was only able to find the correct contact if it was the name stored at:
contacts[0].name
and none of the others. So while trying to figure out what was wrong, I decided to do
cout << contacts.size();
which I thought should output 3, because I have only three contacts stored. Yet for some reason, it output 7. Is there anyway for me to accurately list the number of iterations of Contact stored in the contacts vector in order to get my for loop to work?
Edit for my full code:
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
struct Contact
{
string name;
string address;
string phone;
string email;
};
bool go;
bool a = false;
char command;
string endL = "\n\r";
string tab = "\t";
string line;
int i;
int counter = 0;
int contactCounter = 0;
vector<Contact> contacts;
void add(){
contacts.push_back(Contact());
int newcontact = contacts.size() - 1;
string input;
cout << "Enter the name: " << endL;
cin >> input;
contacts[newcontact].name = input;
cout << "Enter the address: " << endL;
cin >> input;
contacts[newcontact].address = input;
cout << "Enter the phone number: " << endL;
cin >> input;
contacts[newcontact].phone = input;
cout << "Enter the email address: " << endL;
cin >> input;
contacts[newcontact].email = input;
}
void search(string name){
for(int i = 0; i < contacts.size(); i++){
if(contacts[i].name == name){
cout << "Name: " << contacts[i].name << endL << "Address: " << contacts[i].address << endL << "Phone Number: " << contacts[i].phone << endL << "Email: " << contacts[i].email << endL << endL;
a = true;
}
}
if(a == false){
cout << "There is no contact under that name." << endL;
}
}
int main() {
ifstream phonebook;
phonebook.open("phonebook.txt");
if(phonebook.is_open()){
while(getline(phonebook,line)){
if(line.empty() == false){
if(counter % 4 == 0){
contacts.push_back(Contact());
contacts[contactCounter].name = line;
}else if(counter % 4 == 1){
contacts[contactCounter].address = line;
}else if(counter % 4 == 2){
contacts[contactCounter].phone = line;
}else if(counter % 4 == 3){
contacts[contactCounter].email = line;
contactCounter++;
}
counter++;
}
}
}else{cout << "an error has occurred while opening the phonebook";}
phonebook.close();
cout << contacts.size() << endL;
cout << "Enter a command." << endL << tab << "To add a contact, enter '+'" << endL << tab << "To search for a contact, enter 's'" << endL << tab << "To delete a contact, enter '-'" << endL << tab << "To quit the program, enter 'q'" << endL;
cin >> command;
while(command != 'q'){
if(command == '+'){
add();
command = '/';
}
else if(command == 's'){
string searched;
cout << "Please enter who you would like to search for: ";
cin >> searched;
search(searched);
command = '/';
}
else if(command == '-'){
cout << "Not done." << endL;
command = '/';
}
else if(command == '/'){
cout << "Enter a command." << endL << tab << "To add a contact, enter '+'" << endL << tab << "To search for a contact, enter 's'" << endL << tab << "To delete a contact, enter '-'" << endL << tab << "To quit the program, enter 'q'" << endL;
cin >> command;
}
else{
cout << "That command is invalid." << endL;
cout << "Enter a command." << endL << tab << "To add a contact, enter '+'" << endL << tab << "To search for a contact, enter 's'" << endL << tab << "To delete a contact, enter '-'" << endL << tab << "To quit the program, enter 'q'" << endL;
cin >> command;
}
}
ofstream newbook;
newbook.open("phonebook.txt");
if(newbook.is_open()){
for(int i=0; i < contacts.size(); i++){
newbook << contacts[i].name << endl;
newbook << contacts[i].address << endl;
newbook << contacts[i].phone << endl;
newbook << contacts[i].email << endl;
newbook << endL;
}
}else{cout << "there was an issue saving your contacts" << endL;}
newbook.close();
return 0;
}
There's actually nothing wrong with your code except this line
string endL = "\n\r";
Which should really only be
string endL = "\n";
\n is automatically converted to the line endings used by the system, which traditionally is \n (0x0a) on unix systems and \r\n (0x0d0a) on Windows.
But, how did this affect the program so much? Well it only takes affect after the phonebook is written at the end of the program so that phonebook.txt contains these bogus line endings that have \r\n\r at the end (on Windows). So when the file is read, it reads up until the new line \r\n and sees \rPerson Name as line after! Which explains why searching was failing.
You also may see some additional bogus contacts generated because there may be some extra \rs at the end which read as a single line each. Without looking at your phonebook.txt I can't say for certain why you have an additional 4 though I'd guess extra \rs would be the cause.
All in all, use \n for new lines.
To answer the title, vector::size() is THE way to get the number of stored objects in a vector. It's not lying to you.
Using the range based for loop ensures that you won't hit any nonexistent contacts:
for(auto&& contact: contacts)
{
// Contact contact is now accessible.
}
Also, it is probably not a good idea to store a as a global variable. What happens if you execute search twice?
Im having an issue with the last section of coding on here. The // Copy files from infile to outfile. The program transfers my infile which is simply a an 8 digit number , 20392207,splits it up into individual digits using the .at method; and is supposed to save that output to an outfile. I cant figure out how to save the output to the outfile. Any advice?
infile looks as follows
20392207
program output looks like this
The input number :20392207
The number 1:2
The number 2:0
The number 3:3
The number 4:9
The number 5:2
The number 6:2
The number 7:0
The number 8:7
outfile is supposed to look like the program out put, but instead just looks like an exact copy of the infile.
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<cmath>
using namespace std;
int main()
{
string ifilename, ofilename, line, line2;
ifstream inFile, checkOutFile;
ofstream outFile;
char response;
int i;
// Input file
cout << "Please enter the name of the file you wish to open : ";
cin >> ifilename;
inFile.open(ifilename.c_str());
if (inFile.fail())
{
cout << "The file " << ifilename << " was not successfully opened." << endl;
cout << "Please check the path and name of the file. " << endl;
exit(1);
}
else
{
cout << "The file is successfully opened." << endl;
}
// Output file
cout << "Please enter the name of the file you wish to write : ";
cin >> ofilename;
checkOutFile.open(ofilename.c_str());
if (!checkOutFile.fail())
{
cout << "A file " << ofilename << " exists.\nDo you want to continue and overwrite it? (y/n) : ";
cin >> response;
if (tolower(response) == 'n')
{
cout << "The existing file will not be overwritten. " << endl;
exit(1);
}
}
outFile.open(ofilename.c_str());
if (outFile.fail())
{
cout << "The file " << ofilename << " was not successfully opened." << endl;
cout << "Please check the path and name of the file. " << endl;
exit(1);
}
else
{
cout << "The file is successfully opened." << endl;
}
// Copy file contents from inFile to outFile
while (getline(inFile, line))
{
cout << "The input number :" << line << endl;
for (i = 0; i < 8; i++)
{
cout << "The number " << i + 1 << ":";
cout << line.at(i);
cout << endl;
}
outFile << line << endl;
}
// Close files
inFile.close();
outFile.close();
} // main
Here we can see that outFile is only written to outside of the while loop:
while (getline(inFile, line))
{
cout << "The input number :" << line << endl;
for (i = 0; i < 8; i++)
{
cout << "The number " << i + 1 << ":";
cout << line.at(i);
cout << endl;
}
}
outFile << line << endl;
It has no chance of containing the same output as the console
Solution: Write inside the loop the same stuff that was written to the console:
while (getline(inFile, line))
{
cout << "The input number :" << line << endl;
outFile << "The input number :" << line << endl;
blah blah blah
}
But this looks like crap and a function makes like a better solution by eliminating duplication and upping re-usability.
void output(std::ostream & out,
const std::string & line)
{
out << "The input number :" << line << endl;
for (int i = 0; i < 8; i++)
{
out << "The number " << i + 1 << ":";
out << line.at(i);
out << endl;
}
}
and called:
while (getline(inFile, line))
{
output(cout, line);
output(outFile, line);
}
You need to write to outFile inside the while(getline(inFile, line)) loop.
[edit] see user4581301's answer for a more thorough treatment.
I want to write a little program which should be used in supermarkets. everything is fictitious and it's only for learning purposes.
However, The tool generate a new data for every new article. in the data there are 2 lines, the name and the prise.
The data is named as the article number of the product. So the user enter a articlenumber and the tool looks for a data with this number, if it found it, it reads the 2 lines and initiates the variables.
But for some reasons it does not convert and copy the strings correctly.
here is the part which loads the data.
int ware::load()
{
string inhalt;
cout << "please insert article number" << endl;
cin >> articlenumber;
productname.open(articlenumber, ios::in);
if (!productname.is_open())
{
cout << "can't find the product." << endl;
return 1;
}
if (productname.is_open())
{
while (!productname.eof())
{
getline(productname, inhalt);
strcpy(name,inhalt.c_str());
getline(productname, inhalt);
price = atoi (inhalt.c_str());
cout << inhalt << endl;
}
warenname.close();
}
cout << endl << endl <<
"number: " << inhalt <<
" preis: " << price <<
" name: " << name <<
endl << endl; //this is a test and will be deleted in the final
}
hope you can help me!
Here is the class:
class ware{
private:
char articlenumber[9];
char name[20];
int price;
fstream warennamefstream;
ifstream warenname;
public:
void newarticle(); //this to make a new product.
void scan(); //this to 'scan' a product (entering the article number ;D)
void output(); //later to output a bill
int load(); //load the datas.
};
hope everything is fine now.
First, you have a using namespace std; somewhere in your code. This occasionally leads to subtle bugs. Delete it. ( Using std Namespace )
int ware::load()
{
string inhalt;
cout << "please insert article number" << endl;
cin >> articlenumber;
The type of articlenumber is incorrect. Declare it std::string, not char[]. ( What is a buffer overflow and how do I cause one? )
productname.open(articlenumber, ios::in);
There is no reason to have an ifstream lying around waiting to be used. Also, there is no point in providing ios::in -- it is the default. Just use the one-argument form of the ifstream constructor.
if (!productname.is_open())
{
cout << "can't find the product." << endl;
return 1;
}
Don't bother checking to see if the file opened. Your users don't care if the file was present or not, they care whether the file was present AND you retrieved the essential data.
if (productname.is_open())
{
while (!productname.eof())
{
getline(productname, inhalt);
strcpy(name,inhalt.c_str());
getline(productname, inhalt);
price = atoi (inhalt.c_str());
cout << inhalt << endl;
}
warenname.close();
}
This loop is just wrong.
Never invoke eof(). It doesn't do what you think it does, and will cause bugs.
Why is this a loop? Aren't there only two lines in the file?
There is no point in calling close. Just let the file close when the istream goes out of scope.
Why is warename different than productname?
Don't store your data in char[]. This is the 21st century. Use std::string.
.
cout << endl << endl <<
"number: " << inhalt <<
" preis: " << price <<
" name: " << name <<
endl << endl; //this is a test and will be deleted in the final
Never use endl when you mean to say '\n'. Each of those endl manipulators invokes flush, which can be very expensive. ( What is the C++ iostream endl fiasco? )
You forgot to return a value.
Try this instead:
int ware::load()
{
// This declaration should be local
std::string articlenumber;
cout << "please insert article number" << endl;
cin >> articlenumber;
// This declaration should be local
std::ifstream productname(articlenumber.c_str());
// These declarations can be class members:
std::string name;
int price;
std::string number;
if(getline(productname, name) &&
productname>>price &&
productname>>number)
{
cout << "\n\n" <<
"number: " number <<
" preis: " << price <<
" name: " << name <<
"\n\n"; //this is a test and will be deleted in the final
return 0;
} else {
cout << "can't find the product." << endl;
return 1;
}
}