I read other posts but none of them helping at all,
This code have no error still there is bad_alloc error...
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char super[25];
char name[25],last_name[25];
int length;
char *sym = "#";
char *buffer;
ofstream outfile;
outfile.open("farses.dat",ios::app);
cout << "Writing to the file" << endl;
cout << "Enter your First Name: ";
cin >> name;
outfile << *sym;
outfile << name << endl;
cout << "Enter your Last Name: ";
cin >> last_name;
outfile << *sym;
outfile << last_name << endl;
cout << "Enter The Sentence : ";
cin.getline(super,25);
outfile << super << endl;
outfile.close();
ifstream infile;
infile.open("frases.dat");
infile.seekg(0, ios::end);
length = infile.tellg();
infile.seekg(0,ios::beg);
buffer = new char[length];
infile.read(buffer , length);
cout << "\n\nReading from file \n\n" << endl;
cout << buffer << endl;
infile.close();
return 0;
}
This code is terminating after coming to sentence statement..the getline() function is causing problem i guess but when i tried on other two statements(name and last_name),the getline(), it works perfectly..i even degraded the char limit to 5 too but after sentence statement is throw anyways
Thumb rule, don't fool yourself into thinking that your code has no errors. Especially when you clearly got an error. This kind of mindset will make you unable to find errors because everything you see is correct.
You never checked if your streams were open and you entered the wrong file name in the ofstream.
What happens is that, you write your data into a file name farses.dat and then you try to open a file called frases.dat (which I assume is the correct name, it means sentences).
You are getting the cursor position ifstream::tellg of an inexistent file, and it fails so the function returns -1. This is the value of length before you allocate your buffer.
When you do allocate your buffer you get a bad_alloc exception (bad_array_new_length).
Checking if your file was open would, at the very least, have saved you some debug time.
Something like this,
ifstream infile;
infile.open("frases.dat");
if ( infile.is_open() ) {
// File is open, do stuff (...)
if ( length <= 0 ) {
// Empty file / error, don't create buffer!!!
}
// (...)
infile.close();
}
else {
// Couldn't open file
}
EDIT: Fixed error explanation.
Related
I am learning about how to write records on file and read it .
I created a class called student , the class has function like enterStudent , showStudent , printInsideFile (student info) ,...... .
when I try to write student info into the file , it works .
when I try to read all student info from the file , it works
when I try to do both , something unexpected happens (nothing show up)
i thought that the problem with file.flush() , so when i deleted it the output was unreadable text
i could close the file and open it again but i think that is silly
the code is:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class student {
private:
char id[5], name[20], age[5], address[50], gender[5];
public:
void enterStudent() {
cout << "Enter student id : "; cin >> id;
cout << "\nEnter student name : "; cin >> name;
cout << "\nEnter student age : "; cin >> age;
cout << "\nEnter student address : "; cin >> address;
cout << "\nEnter student gender : "; cin >> gender;
}
void showStudent() {
cout << "#########student data##########\n";
cout << "student id : "<< id;
cout << "\nstudent name : " << name;
cout << "\nstudent age : " << age;
cout << "\nstudent address : " << address;
cout << "\nstudent gender : " << gender<<endl;
}
void printInsideFile(fstream &file) {
file.write(id,sizeof(id));
file.write(name, sizeof(name));
file.write(age, sizeof(age));
file.write(address, sizeof(address));
file.write(gender, sizeof(gender));
file.flush();
}
bool readFromFile(fstream &file) {
if (file.eof())
return 0;
file.read(id, sizeof(id));
file.read(name, sizeof(name));
file.read(age, sizeof(age));
file.read(address, sizeof(address));
file.read(gender, sizeof(gender));
if (file.eof())
return 0;
return 1;
}
void showAllFromFile(fstream &file) {
while (this->readFromFile(file))
this->showStudent();
}
};
int main() {
student s;
fstream file;
file.open("a.txt", ios::in | ios::out | ios::app);
if (!file)
goto k270;
s.enterStudent();
s.printInsideFile(file);
//when i read one student , it works okay
//s.readFromFile(file);
//s.showStudent();
//when i try to read multiple students , it doesn't work at all
s.showAllFromFile(file);
file.close();
k270:
system("pause");
return 0;
}
Considering that I have least experience with std::ios::app, I became curious to find out how it actually works.
I made the following MCVE on coliru which (I believe) is working as expected by the OP:
#include <fstream>
#include <iostream>
int main()
{
// open a text file
std::fstream file("test.txt", std::ios::in | std::ios::out | std::ios::app);
// remember current position of read head
file.seekg(0, std::fstream::end); // a trick to update the read head before writing anything
std::fstream::pos_type pos0 = file.tellg();
std::cout << "pos0: " << pos0 << '\n';
// write a line to end of text
std::cout << "Write a line.\n";
file << "A line written by main.cpp" << std::endl;
std::cout << "pos after writing: " << file.tellg() << '\n';
// rewind to remembered position of read head
file.seekg(pos0);
// read the last written line
{ std::string buffer; std::getline(file, buffer);
std::cout << "Last line: '" << buffer << "'\n";
}
// rewind to the beginning of file
file.seekg(0);
// read all
std::cout << "Read all:\n";
for (std::string buffer; std::getline(file, buffer);) {
std::cout << "'" << buffer << "'\n";
}
}
Test Session:
g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp \
&& echo -e "1st line written by echo\n2nd line written by echo\n3rd line written by echo" > test.txt \
; ./a.out
pos0: 75
Write a line.
pos after writing: 102
Last line: 'A line written by main.cpp'
Read all:
'1st line written by echo'
'2nd line written by echo'
'3rd line written by echo'
'A line written by main.cpp'
Notes:
I was fully sure about the file.seekg(0) which is needed before read all to rewind the read file head to the begin of file.
I was not sure about the read the last written lineā¦
I found that the file.seekg(pos0); is necessary.
Obviously, the previous write seems to touch the write head (of course) as well as the read head.
I had some trouble to retrieve the proper read head position using std::istream::tellg().
It returned the expected value after the first file output but not before.
My last resort was a file.seekg(0, std::fstream::end); to move the read head to end of file before anything is written.
I apologize for the total lack of any error checking in the example.
Of course, this has to be added in a serious application.
I left it out to keep the sample code as minimal as possible.
Additionally, I didn't consider the error handling a problem in OPs sample code.
The problem was not the ios::app
It seems that functions file.write() and file.read() change either reading pointer and writing pointer . Even if you use file<<"text"; or file>>array of chars; both of pointers are changing . I searched about it but didn't find explanation but i find the code of ostream::write and istream::read ,they were advanced so if anybody check the link and tell us why
note that ,when the reading pointer points at the end of the file , it will print out nothing
I have been having some problems with my code. I was asked to input elements from an .dat file into an array. For class we have to do this for various files without knowing how many elements will be in each file. The only thing we know is that here will never be more then 5000 elements per file.
One of my input file has the following elements:
5.675207 -0.571210
0.728926 0.666069
2.290909 0.751731 2.004545 0.907396
0.702893 0.646427 5.909504 -0.365045
2.082645 0.871841 5.597107 -0.633507
6.117769 -0.164663 6.091736 -0.190282
5.571074 -0.653433 4.503719 -0.978307
3.983058 -0.745620
3.670661 -0.504729
5.857438 -0.413001
When I run my code:
#define _CRT_NONSTDC_NO_DEPRECATE
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(int argc, char * argv[])
{
ifstream fin;
ofstream fout;
if (argc < 3)
{
cout << "Incorrect usage: prog.exe filenname number" << endl;
cout << "Exiting now, please try again." << endl;
return -1;
}
fin.open(argv[1]);
if (!fin)
{
cout << "Error opening file \"" << argv[1] << "\", exiting." << endl;
return -1;
}
fout.open(argv[2]);
int count = 0;
int word;
double points[5000];
while (fin >> word)
{
fin >> points[count];
++count;
}
fout << "Numer of points is: " << count/2 << endl;
for (int i = 0; i < count; i++)
{
fout << points[i] << " ";
}
fin.close();
fout.close();
return 0;
}
I outputted the elements just to make sure that they were properly inputted. I get the following and I don't know why.
0.675207 0.57121
0.728926 0.666069
0.290909 0.751731 0.004545 0.907396
0.702893 0.646427 0.909504 0.365045
0.082645 0.871841 0.597107 0.633507
0.117769 0.164663 0.091736 0.190282
0.571074 0.653433 0.503719 0.978307
0.983058 0.74562
0.670661 0.504729
0.857438 0.413001
The first digit is converted to a 0 for some reason and the negative ones become positive. Would anyone know why this is occurring?
int word;
is doing you no favours. First it's an integer so fin >> word only reads the integer portion of the inputs. 5.675207 is read as 5. the .675207 is left in the file stream for fin >> points[count]. Words isn't stored anywhere to the 5 is discarded but the .675207 lives on as 0.675207 in points[0].
Where the negative signs are going I didn't bother trying to figure out because
while (fin >> points[count])
{
++count;
}
fixes everything.
When you read in the numbers from the the file you are extracting them as "word" and then storing them as "points". "word" is an integer and "points" is a double, this will give you unexpected behavior. The compiler should give you warnings about this.
I'm quite new to C++ programming, and I'm having trouble reading from an already open file. What I'm doing is writing to a file, reading from it, adding to the end of it, and then trying to read from it again without having to close the original ifstream. The code is as follows:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream myFile ("example.dat");
// Open and write to file
if (myFile.is_open())
{
myFile << "This is a line." << endl;
myFile << "This is another line." << endl;
myFile.close();
}
else cout << "no";
// Open and read from file
string line;
ifstream myFilein ("example.dat");
if (myFilein.is_open())
{
while (getline(myFilein,line))
{
cout << line << myFilein.tellg() << endl;
}
//myFilein.close();
}
// Open and add to end of file
if (!myFile.is_open())
{
myFile.open("example.dat", ios::app);
myFile << "This is the last line." << endl;
myFile.close();
}
//myFilein.open("example.dat", ios::ate);
// Read from already open file
myFilein.seekg(0, ios::beg);
if (myFilein.is_open())
{
cout << "myFilein is open. " << myFilein.tellg() << endl;
while (!myFilein.eof())
{
getline(myFilein, line);
cout << line << endl;
}
}
myFilein.close();
int holdClose;
cin >> holdClose;
return 0;
}
Obviously, something is going wrong, as tellg() is returning a value of -1 after the initial read (i.e., after it hits the end of the file), but I'm not entirely sure why it's returning -1, since I'm trying to reset the position to the beginning of the file. Is there something I'm missing or misunderstanding about how this works? If I close and re-open the file, then it's fine, but I'm curious if there's a way to keep reading from it without having to close it, if that makes sense. Thank you for your help :)
You didn't clear the state of the stream, thus the seekg call did nothing. You need to add myFilein.clear() before the repositioning.
I am trying to read the contents of a text file into a 2D string array, but no matter what I have tried or searched, I can not find a solution. The code is supposed to load a text file separate it into elements by finding horizontal tabs and display the output. When I run the code as is, I receive an error that I found out from searching online, means that I'm trying to manipulate memory I shouldn't be. I'm not asking for the code to be written, just a push in the right direction. Thank you in advance.
this is what I get when I run the program:
0x23fd5c
Process returned -1073741819 (0xC0000005) execution time : 2.344 s
Press any key to continue.
EDIT:: I have corrected the code so it now functions as it should, but it is not storing the last entry of each line in the text file correctly. I can somehow display the number 100 which is the last entry, but when I try to pass that location or display just playList[0][5] , it says it is equal to the first entry of the next line. Any help would be amazing I posted the current code below.
here is my code:
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
using namespace std;
void readTextFile( int &Count, string playList[50][5]);
void userAddition( int &Count, string playList[50][5]);
int main()
{
string decision;
string playList[50][5];
int Count = 0;
readTextFile(Count, playList);
cout << "If you would like to add to the list, Please enter 'Y'. If you would like to exit
please enter 'N'. ----> ";
getline(cin, decision);
if (decision=="y" || decision=="Y")
userAddition(Count, playList);
else
{
return(0);
}
return 0;
} // End of Main FN.
void readTextFile( int &Count, string playList[50][5])
{
string inputfield;
ifstream infile("c:\\cTunes.txt", ifstream::in);
if ( infile.is_open() )
{
// File is read.
} // end if
else
{
cout << "Error Opening file" << endl;
return; //Program Closes.
} // end else
cout << setw(30)<<left<< "TITLE"<< setw(10) <<left<<"LENGTH"<<
// Outputs a title to each column that is displayed.
setw(40)<< left<<"ARTIST"<< setw(40) << left<<"ALBUM"<<
setw(15) << left <<"GENRE" << setw(5) << left << "RATING" << endl;
getline(infile, inputfield, '\t'); // read until tab
while(! infile.eof()) // loop until file is no longer valid.
{
playList[Count][0] = inputfield;
getline(infile, inputfield, '\t'); // read until tab.
playList[Count][1] = inputfield;
getline(infile, inputfield, '\t'); // read until tab.
playList[Count][2] = inputfield;
getline(infile, inputfield, '\t'); // read until tab.
playList[Count][3] = inputfield;
getline(infile, inputfield, '\t'); // read until tab.
playList[Count][4] = inputfield;
getline(infile, inputfield); // read until end of line.
playList[Count][5] = inputfield;
cout << setw(30)<<left<< playList[Count][0] << setw(10) <<left<<playList[Count][1] <<
// Output the line number equal to count.
setw(40)<< left<<playList[Count][2] << setw(40) << left<< playList[Count][3] <<
setw(15) << left << playList[Count][4] << setw(5) << left << playList[Count][5] <<
endl;
/*cout <<"Title: " << setw(25)<<left<< playList[Count][0]<<endl;
cout <<"Length: " << setw(5) <<left<<playList[Count][1] << endl;
cout <<"Artist: " << setw(50)<< left<<playList[Count][2] << endl;
cout <<"Album: " << setw(40) << left<< playList[Count][3] << endl;
cout <<"Genre: " << setw(15) << left << playList[Count][4] << endl;
cout <<"Rating: " << setw(5) << left << playList[Count][5] << endl<<endl;*/
Count++; // Increment counter by 1
getline(infile, inputfield, '\t'); // read next line until tab.
} // end while
infile.close(); // close the file being read from.
cout<<endl<<endl<<playList[0][5]<<endl;
} // End of readTextFile
I believe getline is causing the problem when reading till the end of the line but I'm truly at a loss.
First, note that in the following line:
cout << playList << endl;
you are printing the address of the array, not the contents. you will need
a loop to print the contents.
Second, in the following code:
if ( infile.is_open() )
{
// ok, read in the file
} // end if
else
{
cout << "Error Opening file" << endl;
//a return statement is missing
}
you need a return statement to avoid reading from a closed stream (which can cause a crash)
Finally, your function does not return anything, so it should either be declared void
or return some value (in which there is no sense according to the context).
Hope that helps and good luck!
The readTextFile function does not return anything. You need to return a string. If you are getting the error what(): basic_string::_S_construct null not valid then this is your problem. You can avoid similar problems by using -Wall compiler option.
You are using std::string for storing the string, std::ifstream for reading from a file, std::getline for reading words... you should really use std::vectors instead of arrays:
typedef std::vector<std::string> Line;
std::vector<Line> playList;
It will make things easier for you.
I also recommend you to change the way you read from a file to:
while(getline(...))
{
...
}
But since you are not allowed to use std::vector, your function could look like this:
// reads the content of input file and stores it into playList:
void readTextFile(std::ifstream& infile, std::string playList[][5])
{
std::string line;
for (int lineIndex = 0; getline(infile, line); ++lineIndex)
{
// skip empty lines:
if (line.empty()) continue;
std::string word;
std::istringstream lineStream(line);
for (int wordIndex = 0; getline(lineStream, word, '\t'); ++wordIndex)
{
// skip empty words:
if (line.empty()) continue;
playList[lineIndex][wordIndex] = word;
}
}
}
that could be used like this:
std::string playList[19][5];
std::ifstream infile("c:\\Test.txt");
if (infile.is_open())
{
readTextFile(infile, playList);
infile.close();
}
else
std::cout << "Error Opening file" << std::endl;
Also note that cout << playList << endl; outputs the address of the first word. To print all words, you will have to write a loop.
Can someone with a little time on their hands please compile and run this code and see where I am going wrong?
#include <iostream>
#include <fstream>
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::ios;
int main()
{
int numbers = 0;
//create and open file
ifstream inFile;
ofstream outFile;
inFile.open ("numbers.txt", ios::in);
outFile.open ("evenNumbers.txt", ios::out);
//determine whether the file was opened
if (inFile.is_open() && outFile.is_open())
{
//read numbers file
inFile >> numbers;
while (!inFile.eof())
{
//look for even numbers
if (numbers %2 == 0)
{
outFile << numbers << endl;
//cout << numbers << endl;
}
inFile >> numbers;
}
//end while
//close files
outFile.close();
inFile.close();
cout << "Program successful. File complete." << endl;
}
//if file fails to open, display error message
else
cout << " File could not be opened " << endl;
//end if
system ("pause");
return 0;
} //end of main function
Your code has quite a few problems:
ifstream inFile;
inFile.open("numbers.txt", ios::in);
It's not exactly an error, but ios::in is the default for an ifstream, and you typically supply the file name to the constructor, something like this:
ifstream inFile("numbers.txt");
Then we have this:
getline(inFile, name);
inFile >> num;
while (inFile.eof())
while (inFile.eof()) seems to have the logic backwards -- you want to read until you reach the end of the, then quit. The rest of your loop will work (unusual for one that uses file.eof() as the condition) but is unnecessarily long and difficult to read.
//create file object and open the file
ofstream outFile;
outFile.open("updatedNumbers.txt", ios::out);
As you'd expect from the previous comment, ios::out is the default for an ofstream, and you usually give the file name to the constructor: ofstream outFile("updatedNumbers.txt");
//write the updated numbers to the file
outFile << heading << endl;
outFile << columnHeaders << endl;
outFile << underLines << endl;
heading, columnHeadders and underLines seem to be undefined variables.
for (x=0;x<20; x++)
{
if (int x%2==0)
sample[x] = x+2;
else
sample[x] = x+20;
sample also seems to be undefined.
outFile << num[x] << endl;
num also seems to be undefined. Perhaps you intended it to be the same as sample? Otherwise, you don't seem to have any code to set it to any particular value before you write it out.
Probably worse than any of that is the fact that your heading talks about writing the even numbers from one file to another, but your code doesn't seem to do anything even vaguely similar to that at all.
Well, the heading variable is undeclared, but I guess you already know that....
The error is here:
outFile << heading << endl;
outFile << columnHeaders << endl;
outFile << underLines << endl;
This is the first time you these variables heading, columnHeaders and underLines are mentioned in your program. The compiler complains because they have not been declared anywhere (Should they be int or std::string ore some other type?). Also they won't contain any useful values because nothing has been assigned to them.