getline() function is not working in while loop - c++

I want to make a simple file input output program with an external class "File_Opening_and_Closing.cpp” when I use ”getline ()” function without any loop it works fine but when I use ”getline ()” function with do while loop in “main.cpp” it crushes.
Please tell me where the problem is and how I solve it?
main.cpp
#include<iostream>
#include<fstream>
#include "File_Opening_and_Closing.h" using namespace std;
int main() {
int i=1;
char file_make='y';
char file_insert='y';
do
{
File_Opening_and_Closing file[i];
do
{
file[i].put_data();
file[i].show_data();
cout<<"Do you want to insert text again ? 'y' OR 'n'"<<endl;
cin>>file_insert;
}while(file_make=='y');
i++;
cout<<"Do you want to Make another file ? 'y' OR 'n'"<<endl;
cin>>file_make;
}while(file_insert=='y');
return 0;}
with out loop working fine >>
int main() {
File_Opening_and_Closing file;
file.put_data();
file.show_data();
return 0;}
File_Opening_and_Closing.cpp
#include "File_Opening_and_Closing.h"
File_Opening_and_Closing::File_Opening_and_Closing()
{
cout<<"Enter the file name and type => ";
cin>>file_name;
}
void File_Opening_and_Closing::put_data(){
ofstream file_out;
file_out.open(file_name);
cin.ignore();
cout<<"Enter the string => ";
cin.ignore();
// getline is not working here!
getline(cin,data);
data = "Hello World!";
file_out<<data;
file_out.close();
}
void File_Opening_and_Closing::show_data(){
ifstream file_in;
file_in.open(file_name);
getline(file_in,data);
cout<<data;
file_in.close();
}
File_Opening_and_Closing.h
#ifndef FILE_OPENING_AND_CLOSING_H
#define FILE_OPENING_AND_CLOSING_H
#include<iostream>
#include<fstream>
using namespace std;
class File_Opening_and_Closing
{
private:
string file_name;
string data;
public:
File_Opening_and_Closing();
void put_data();
void show_data();
protected:
};
#endif // FILE_OPENING_AND_CLOSING_H
Problem picture

You have a whole host of issues, not the least of what is a How to debug small programs issue where you have mixed up the variables used to test both do .. while (...); loops, e.g.
...
cin>>file_insert;
}while(file_make=='y');
// i++; (not needed and VLA's not allowed in C++
cout<<"Do you want to Make another file ? 'y' OR 'n'"<<endl;
cin>>file_make;
}while(file_insert=='y');
Secondly, as mentioned in the comments, Standard C++ does not allow Variable Length Arrays.
File_Opening_and_Closing file[i];
If you need more than 1 instance of your class, the use a vector of classes or array of classes. However, there is no need in your code for either. Since you create a new instance of File_Opening_and_Closing each iteration through the do { ... } while (..); loop, you can simply use:
File_Opening_and_Closing file;
You are making things incredibly hard on yourself by declaring file_make and file_insert as type char. Instead, simply make them std::string and test with, e.g. if (file_make == "y"). This will allow you to read all input with getline avoiding the problems with mixed std::cin and getline use.
The remaining issues are a complete failure to validate the file openings with, e.g. if (!file_out.is_open()) { /* handle error */ } with similar tests needed for each input to ensure you can trap a input cancellation by the user generating a manual EOF with Ctrl+d (or Ctrl+z on windows).
Also, avoid putting using namespace std; in header files. There is no need to pull the standard namespace into every file utilizing your header (though you did do a good job and protect against multiple inclusions with the header guards FILE_OPENING_AND_CLOSING_H). In fact there is no reason for using namespace std; at all here. Just use the std:: namespace resolution operator for cin, cout, etc..
Leaving the validations for you to add, addressing the other issues, you could do something similar to:
File_Opening_and_Closing.h
#ifndef FILE_OPENING_AND_CLOSING_H
#define FILE_OPENING_AND_CLOSING_H
#include<iostream>
#include<fstream>
class File_Opening_and_Closing
{
private:
std::string file_name;
std::string data;
public:
File_Opening_and_Closing();
void put_data();
void show_data();
protected:
};
#endif
File_Opening_and_Closing.cpp
#include "File_Opening_and_Closing.h"
File_Opening_and_Closing::File_Opening_and_Closing()
{
std::cout << "Enter the file name and type => ";
getline (std::cin, file_name);
}
void File_Opening_and_Closing::put_data(){
std::ofstream file_out;
file_out.open(file_name);
std::cout<<"Enter the string => ";
getline (std::cin, data);
file_out << data << '\n';
file_out.close();
}
void File_Opening_and_Closing::show_data(){
std::ifstream file_in;
file_in.open (file_name);
getline (file_in,data);
std::cout << data << '\n';
file_in.close();
}
main.cpp
#include<iostream>
#include<fstream>
#include "File_Opening_and_Closing.h"
int main (void) {
std::string file_make = "y";
std::string file_insert = "y";
do
{
File_Opening_and_Closing file;
do
{
file.put_data();
file.show_data();
std::cout << "Do you want to insert text again ? 'y' OR 'n'\n";
getline (std::cin, file_insert);
} while (file_insert == "y");
std::cout << "Do you want to Make another file ? 'y' OR 'n'\n";
getline (std::cin, file_make);
} while (file_make == "y");
return 0;
}
It will now create as many files as you need (though you will want to look into std::ios::app mode if you want to add more than one string.
Example Use/Output
$ ./bin/main
Enter the file name and type => out1
Enter the string => foobar
foobar
Do you want to insert text again ? 'y' OR 'n'
y
Enter the string => barbaz
barbaz
Do you want to insert text again ? 'y' OR 'n'
n
Do you want to Make another file ? 'y' OR 'n'
y
Enter the file name and type => out2
Enter the string => bazbuz
bazbuz
Do you want to insert text again ? 'y' OR 'n'
n
Do you want to Make another file ? 'y' OR 'n'
n
Resulting Output Files
$ cat out1
barbaz
$ cat out2
bazbuz
Let me know if you have further questions.

Related

Using a function to open a file and then having other functions utilize that file afterwards?

I have a computer science assignment which requires me to have a separate function just to open the file, and then another function which will then process the data in that file and then some others to do some operations with that data. Anyways, I'm having trouble in how to be able to let other functions use that opened file. References with '&' or'*' are confusing me and I'm unsure if I have to use one or not, of course, though I'm pretty sure I'll have to pass at least something to the next function. The main intent when dealing with the file is to open it(openFile) and then have another function(getData) to sort the data into two different arrays. One for the names, and one for the amounts next to them. The file would be written as:
Johnson 6000
Brown 5000
Miller 4000
Duffy 2500
Robson 1800
My code is as follows:
'''
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
void openFile();
void getData();
void computePercentages();
void sortVotes();
void display();
void displayWinner();
int main() {
openFile();
getData();
return 0;
}
void openFile(){
string fileName;
cout << "Enter the name of the file to open: ";
cin >> fileName;
ifstream file;
file.open(fileName.c_str());
}
void getData(){
int count = 0;
while(!file.eof()){
string names[count];
int votes[count];
cin >> names[count];
cin >> votes[count];
count ++;
}
}
'''
One way is to have openFile return the file stream object, then pass it to getData.
ifstream openFile()
{
string fileName;
cout << "Enter the name of the file to open: ";
cin >> fileName;
ifstream file(fileName);
return file;
}
void getData(ifstream &file)
{
int count = 0;
while(file){
string names[count];
int votes[count];
cin >> names[count];
cin >> votes[count];
count ++;
}
}
int main()
{
ifstream file = openFile();
if (file)
{
getData(file);
}
}
Note that this answer does not fix other issues in your code. For example, in getData you're using variable-length arrays which are non-standard and won't work on all compilers, and those arrays are constructed and destroyed each time through the while loop.
There are many ways to do it..
Here is a simple way.. using global variables.
I made ifstream file; as global..
This is not good way.. but simple..
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
void openFile();
void getData();
void computePercentages();
void sortVotes();
void display();
void displayWinner();
ifstream file;
int main() {
openFile();
getData();
return 0;
}
void openFile(){
string fileName;
cout << "Enter the name of the file to open: ";
cin >> fileName;
file.open(fileName.c_str());
}
void getData(){
int count = 0;
while(!file.eof()){
string names[count];
int votes[count];
cin >> names[count];
cin >> votes[count];
count ++;
}
}
Your getData() function has some problems:
void getData(){
int count = 0;
while(!file.eof()){ // this is almost never the correct check
string names[count]; // you declare new VLA:s (non-standard) every iteration
int votes[count]; // -"-
cin >> names[count]; // and you put a value in it out of bounds.
cin >> votes[count]; // -"-
count ++;
} // both arrays are destroyed here
}
file.eof() does not return true until you've tried to read beyond the end of the file. If you've read the last value, it will not be set. Only when you try next time will it be set.
The arrays you declare inside the while loop will be destroyed at the end of the loop. After the loop is finished, you have no arrays.
When you declare an array of count elements, you can access those elements using 0 to count-1 inclusive. You access element count which is out of bounds so your program has undefined behaviour.
VLA:s (variable length arrays) does not exist in standard C++ (but does as an extension in some compilers). If you know exactly how many elements you need to store, you can use std::array instead, but in this case, use a std::vector.
It uses a global file variable (that doesn't even exist). Try to stay away from global variables if you can.
The records in your data file should be kept together instead of putting each column in a separate array. A simple placeholder for each record in your file could look like this:
struct record {
std::string name{};
int vote{};
};
With that, you only need one array (or std::vector).
std::vector<record> records;
It'd also be good if one could extract one complete record from a stream using the same >> operator as you used for int and std::string. Like this:
record temp; // declare a variable using your own type, "record"
while(file >> temp) { // read records until no more can be read
records.push_back(temp) // add one record to records
}
A function to read one record from an istream, like an ifstream:
std::istream& operator>>(std::istream& is, record& r) {
// You may want to use getline here instead in case the names contain spaces.
return is >> r.name >> r.vote; // extract name and vote from is and return is
}
The function takes both parameters (is and r) by reference. That means that whatever is done to the parameters inside the function affects the variables that were used to call the function. file >> temp results in a call to the above function where is is a reference to file and r is a reference to temp.
For openFile() I'd suggest:
std::ifstream openFile(const std::string& fileName) { // return the ifstream by value
return std::ifstream{fileName};
}
Getting the filename from the user doesn't have anything to do with opening the file, so get the filename before calling the function. The above function lets you call openFile() and get an ifstream in return:
std::ifstream file = openFile(fileName);
You can now call getData() using file, but it needs to be able to receive it. Standard stream objects can't be copied (passed by value), but we don't need to. Just make getData() receive a reference to the stream. I'd make it an istream instead of an ifstream to be able to read from any istream decendant:
std::vector<record> getData(std::istream& is) {
// create a vector, read data from "is" and put it in vector and return vector when done
}
When all is pieced together, you could have a main() looking something like this:
int main() {
std::vector<record> records;
std::cout << "Enter the name of the file to open: ";
// use getline since a filename may contain spaces
if(std::string fileName; std::getline(std::cin, fileName)) {
// if "file" is in a good state after openFile(), call getData()
if(std::ifstream file = openFile(fileName)) {
records = getData(file);
} // "file" is automatically closed when it goes out of scope
}
// print what you collected
for(const record& r : records) {
std::cout << r.name << "\t" << r.vote << "\n";
}
}
The above uses If Statements with Initializer which is a C++17 feature to help create a narrow scope for variables.

Reading string then int line by line in C++

So, I have a file that contains a pattern of a string then an int alternating line by line.
Something like this:
John McClane
30
James Bond
150
Indiana Jones
50
In this example, I would set John McClane to a string variable and then 30 to an integer variable. My issue is dealing with two types. I want to use getline(), but that only works with strings.
Is there an efficient or "right" way of doing this?
There are a number of approaches you could try.
Get string input, and convert to an integer if valid
Convert every second string to an integer
Try to read an integer when you expect one (just using cin >> in;). If you want a robust program, you can check validity with cin.good()
I don't know if there is a "right" way of doing this per say, but it's not a very taxing operation, so whatever you choose should be fine.
You could make a variable like this
string ibuf;
Then convert it to an integer doing this
getline(cin, ibuf);
(Whatever your int variable is) = strtol(ibuf.c_str(), NULL, 10);
One thing about C++ is that there are a large number of ways to accomplish any one task. One way to get integers from strings is to use a stringstream. There is a tutorial on stringstreams here
As for your problem with reading the alternating file, consider the following pseudocode:
boolean isInt = false;
while(fileIsNotOver) {
//getline
if(isInt) {
//use stringstream to get int here
} else {
//do whatever with the name here
}
isInt = !isInt;
}
I don't know if this fully works as i didn't tested it however it just compiles fine and answer should be something like this i think.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
int counter = 0;
int number;
string test_string;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,test_string) )
{
cout << test_string << '\n';
++counter;
if(counter % 2 == 0 ){
number = atoi(test_string.c_str());
cout << number << '\n';
}else{
cout << test_string << '\n';
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
You can try like this to read a string then an int alternating line by line.
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
int main()
{
string name;
int number;
freopen("input.txt", "r", stdin);
while (getline(cin, name))
{
cin >> number;
/*
process the input here
...
...
*/
getline(cin, name); // just to read the new line and/or spaces after the integer
//getchar(); //you can use getchar() instead of getline(cin, name) if there is no spaces after the integer
}
return 0;
}
Thanks !!!

File Handling not working in while loop

Code:
#include<iostream.h>
#include<fstream.h>
#include<string.h>
int n = 0, flag = 0,i;
struct bac
{
char name[10];
char amt[5];
} s;
void main()
{
ofstream f("C:\\TC\\1.dat");
for(i=0;i<10;i++)
{
cout << "\nenter the details ";
cin >> s.name >> s.amt;
f.write((char *)&s, sizeof(bac));
}
}
sometimes the code works fine
but at the other times , when i look at the output file,it is empty , the problem has come up many times , and i ant to know whether there is a precaution regarding loops with file handling
for eg. in other program
.....
while(ch!=4)
{
cout << "\nBANK MANAGEMENT SYSTEM \n";
cout << "enter choice ";
cout << "\n1.add\n2.search\n3.delete and overwrite ";
cin >> ch;
if (ch == 1)
{
cout << "\nenter the details ";
cin >> s.name >> s.amt;
f.write((char *)&s, sizeof(bac));
}
.....
the file is empty
I guess you may have used a very old compiler older than gcc 4.5.3.
I tried your code and it has no problem.
#include <iostream> //use header file without using deprecated iostream.h
#include <fstream> //same reason as above
#include <string>
using namespace std;
int n = 0, flag = 0,i;
struct bac
{
char name[10];
char amt[5];
} s;
int main() //usually main returns int. void was kind of old now
{
ofstream f("test.txt");
for(i=0;i<10;i++)
{
cout << "\nenter the details ";
cin >> s.name >> s.amt;
f.write((char *)&s, sizeof(bac));
}
f.flush();
f.close();
return 0;
}
I compiled the code in gcc 4.5.3 and ran it. the file has all the stuff I entered.
However, it will be better to use the << operator when you use file i/o stream to write to file.
You can find more information about and from top of this link:
http://members.gamedev.net/sicrane/articles/iostream.html
Another point, wen you have done writing to a file, remember to flush and close the file handle, otherwise, sometimes it will cause some annoying problems.
The code doesn't seem very C++-like to me...
To answer the last question, there aren't any gotchas about fstreams in loops specifically, no.
I suggest first trying to do f.write with the members name and amt themselves—compilers might add padding between name and amt, creating unwanted garbage output.
Are you sure you have write permission to the filepath all the time? Try opening a local file, as in the path being simply "1.dat".
Also try opening the file as f("/* file name */", ofstream::out | ofstream::app). "out" sets it as an output stream, and "app" makes it add to the end of the file. www.cplusplus.com/ofstream details more flags.
since you are using c++, I suggest you use a formal way to use ofstream, in your code, it should be f << s.name << s.amt.
remember, you are using c++, so keep using i/o stream.

Loop to check existence of file and process it

I am starting the first part of a school assignment and I must prompt the user to enter a filename, check for the existence of the file, and if it exists, open it for processing; otherwise I am to have the user enter another filename.
When I compile and run my program below, I get the error message "No file exists. Please enter another filename." When I type in names of files that don't exist it just runs the first part of my do while loop again. I'm a beginner at C++ but I've done this before and I feel as if it should be running properly. Any help would be appreciated.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct customerData
{
int _customerID;
string _firstName, _lastName;
double _payment1, _payment2, _payment3;
};
void processFile();
int main()
{
processFile();
system ("pause");
return 0;
}
void processFile()
{
string filename;
ifstream recordFile;
do
{
cout << "Please enter a filename\n";
cin >> filename;
recordFile.open(filename);
if (recordFile.good())
// {
// enter code for if file exists here
// }
;
}
while(recordFile.fail());
{
cout << "No file by that name. Please enter another filename\n";
cin >> filename;
recordFile.open(filename);
}
}
To check whether a file was successfully opened you must use the std::fstream::is_open() function, like so:
void processfile ()
{
string filename;
cout << "Please enter filename: ";
if (! (cin >> filename))
return;
ifstream file(filename.c_str());
if (!file.is_open())
{
cerr << "Cannot open file: " << filename << endl;
return;
}
// do something with open file
}
The member functions .good() and .fail() check for something else not whether the file was opened successfully.
I'm not 100% sure what your intent is here, but do you understand that you've only got one loop here? After your do/while loop, you've got some code in braces, but that's not connected to any loop construct... it's simply a new scope (which doesn't serve a purpose here).
So, your program does this:
1) Ask for filename. Try to open it. If file stream can be read, do the "enter code here" part.
2) Check if filestream is "bad". if so, go back to step 1. Otherwise, continue.
3) Print out "no file by that name", prompt for a new file, try to open it
That's almost certainly not what you want.
You can use c code.
FILE *fp = fopen("file" "r");
if(fp){
//do stuff
}
else{
//it doesnt exist
}
on a side note, when using namespace std try to make it not global
you can put it inside of your functions instead when necessary
int main(){
using namespace std;
//other std stuff
}

Reading a full line of input

I'm trying to store the input that user enters through console. so I need to include the "enter" and any white space.
But cin stops giving me input after the first space.
Is there a way to read whole lines until CTRL+Z is pressed, or something?
is there a way like readLines till CTRL+Z is pressed or something ??
Yes, precisely like this, using the free std::getline function (not the istream method of the same name!):
string line;
while (getline(cin, line)) {
// do something with the line
}
This will read lines (including whitespace, but without ending newline) from the input until either the end of input is reached or cin signals an error.
#include <iostream>
#include <string>
using namespace std;
int main()
string s;
while( getline( cin, s ) ) {
// do something with s
}
}
For my program, I wrote the following bit of code that reads every single character of input until ctrl+x is pressed. Here's the code:
char a;
string b;
while (a != 24)
{
cin.get(a);
b=b+a;
}
cout << b;
For Ctrl+z, enter this:
char a;
string b;
while (a != 26)
{
cin.get(a);
b=b+a;
}
cout << b;
I can't confirm that the ctr+z solution works, as I'm on a UNIX machine, and ctrl+z kills the program. It may or may not work for windows, however; You'd have to see for yourself.
#include <string>
#include <iostream>
int main()
{
std::cout << "enter your name: ";
std::string name;
std::getline(std::cin, name);
return 0;
}
You can use the getline function in c++
#include<iostream>
using namespace std;
int main()
{
char msg[100];
cin.getline(msg,100);
return 0;
}