How do you get a file in C++? - c++

So the teacher has posed this assignment:
You have been hired by the United Network Command for Law Enforcement, and you have been given files containing null cyphers you have to decrypt.
So for the first file given (as an example), every other letter is correct (ie: 'hielqlpo' is hello (assuming you start with the first letter). My first question is, how do I read in a file? The document is on my desktop in a folder and the file is named document01.cry. I'm not sure the command I need to put that file into the program.
I'm also not overly sure how to grab a letter and skip a letter, but honestly I want to tinker with that before I post that question! So for now...my question is as stated in the title: How do you grab a file for reading in C++?
If it makes a difference (As I'm sure it does), I'm using Visual C++ 2008 Express Edition (because it's free and I like it! I've also attached what I have so far, please keep in mind it's -very- basic...and I added the getchar(); at the end so when it does run properly, the window stays open so I can see it (as Visual Express tends to close the window as soon as it's done running.)
The code so far:
#include<iostream>
using namespace std;
int main()
{
while (! cin.eof())
{
int c = cin.get() ;
cout.put(c) ;
}
getchar();
}
PS: I realize that this code grabs and puts out every character. For now that's fine, once I can read in the file I think I can tinker with it from there. I'm also poking at a book or two I have on C++ to see it anything pops up and screams "Pick me!" Thanks again!
EDIT:: Also curious, is there a way to input the file you want?
(I.e.:
char filename;
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename;
cout << endl;
ifstream infile(filename, ios::in);
This code doesn't work. It shoots back an error saying the char can't be converted to a const char *. How can this problem be fixed?
EDIT 2:
Never mind about said part 2, I found it out! Thanks again for the assistance!

To do file operations, you need the correct include:
#include <fstream>
Then, in your main function, you can open a file stream:
ifstream inFile( "filename.txt", ios::in );
or, for output:
ofstream outFile( "filename.txt", ios::out );
You can then use inFile as you would use cin, and outFile as you would use cout. To close the file when you are done:
inFile.close();
outFile.close();

[EDIT] include support for command line arguments
[EDIT] Fixed possible memory leak
[EDIT] Fixed a missing reference
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char *argv){
ifstream infh; // our file stream
char *buffer;
for(int c = 1; c < argc; c++){
infh.open(argv[c]);
//Error out if the file is not open
if(!infh){
cerr << "Could not open file: "<< argv[c] << endl;
continue;
}
//Get the length of the file
infh.seekg(0, ios::end);
int length = infh.tellg();
//reset the file pointer to the beginning
is.seekg(0, ios::beg);
//Create our buffer
buffer = new char[length];
// Read the entire file into the buffer
infd.read(buffer, length);
//Cycle through the buffer, outputting every other char
for(int i=0; i < length; i+= 2){
cout << buffer[i];
}
infh.close();
}
//Clean up
delete[] buffer;
return 0;
}
Should do the trick. If the file is extremely large, you probably shouldn't load the entire file into the buffer.

Although your queston has been answered, two little tips:
1) Instead of counting x and y to see if you are on an odd or even character you can do the following:
int count=0;
while(!infile.eof())
{
infile.get(letter);
count++;
if(count%2==0)
{
cout<<letter;
}
}
% essentially means 'remainder when divided by,' so 11%3 is two. in the above it gives odd or even.
2) Assuming you only need to run it on windows:
system("pause");
will make the window stay open when its finished running so you don't need the last getchar() call (you may have to #include<Windows.h> for that to work).

I figured it out! To be honest no one answer helped, it was a combination of the three, plus the comments from them. Thank you all very much! I've attached the code I used, as well as a copy of the document. The program reads in every character, then spits out the deciphered text. (IE: 1h.e0l/lqo is hello) The next step (extra credit) is to set it up so the user inputs how many characters to skip before reading in the next character to input.
This step I intend to do on my own, but again, thank you very much for all the assistance everyone! Proving once again how awesome this site is, one line of code at a time!
EDIT:: Code adjusted to accept user input, as well as allow for multiple uses without recompiling (I realize it looks like a huge sloppy mess, but that's why it's EXTREMELY commented...because in my mind it looks nice and neat)
#include<iostream>
#include<fstream> //used for reading/writing to files, ifstream could have been used, but used fstream for that 'just in case' feeling.
#include<string> //needed for the filename.
#include<stdio.h> //for goto statement
using namespace std;
int main()
{
program:
char choice; //lets user choose whether to do another document or not.
char letter; //used to track each character in the document.
int x = 1; //first counter for tracking correct letter.
int y = 1; //second counter (1 is used instead of 0 for ease of reading, 1 being the "first character").
int z; //third counter (used as a check to see if the first two counters are equal).
string filename; //allows for user to input the filename they wish to use.
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename; //getline(cin, filename);
cout << endl;
cout << "'Every nth character is good', what number is n?: ";
cin >> z; //user inputs the number at which the character is good. IE: every 5th character is good, they would input 5.
cout << endl;
z = z - 1; //by subtracting 1, you now have the number of characters you will be skipping, the one after those is the letter you want.
ifstream infile(filename.c_str()); //gets the filename provided, see below for incorrect input.
if(infile.is_open()) //checks to see if the file is opened.
{
while(!infile.eof()) //continues looping until the end of the file.
{
infile.get(letter); //gets the letters in the order that that they are in the file.
if (x == y) //checks to see if the counters match...
{
x++; //...if they do, adds 1 to the x counter.
}
else
{
if((x - y) == z) //for every nth character that is good, x - y = nth - 1.
{
cout << letter; //...if they don't, that means that character is one you want, so it prints that character.
y = x; //sets both counters equal to restart the process of counting.
}
else //only used when more than every other letter is garbage, continues adding 1 to the first
{ //counter until the first and second counters are equal.
x++;
}
}
}
cout << endl << "Decryption complete...if unreadable, please check to see if your input key was correct then try again." << endl;
infile.close();
cout << "Do you wish to try again? Please press y then enter if yes (case senstive).";
cin >> choice;
if(choice == 'y')
{
goto program;
}
}
else //this prints out and program is skipped in case an incorrect file name is used.
{
cout << "Unable to open file, please make sure the filename is correct and that you typed in the extension" << endl;
cout << "IE:" << " filename.txt" << endl;
cout << "You input: " << filename << endl;
cout << "Do you wish to try again? Please press y then enter if yes (case senstive)." ;
cin >> choice;
if(choice == 'y')
{
goto program;
}
}
getchar(); //because I use visual C++ express.
}
EDIT:::
I tried inserting the text, but I couldn't get it to come out right, it kept treating some of the characters like coding (ie an apostrophe apparently is the equivalent of the bold command), but you could just try putting in "0h1e.l9lao" without the parenthesis into a .txt and it should give the same outcome.
Thanks again everyone for the help!

Related

C++ Reading text file with delimiter into struct array

I am trying to read data from a text file formatted similarly to this:
knife, object, 0
bag, object, 15
kitchen, room, 400
Into an array composed of structures. Here is what I have so far, but it only reads the first element then returns garbage.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct itemlist
{
string type;
string selltype;
int price;
int diditsell=0;
};
int main()
{
string filename;
cout << "Please enter a file name. " << endl;
cin >> filename;
ifstream in(filename);
itemlist c[100];
for (int i=0;i<100;i++)
{
in >> c[i].type >> c[i].selltype >> c[i].price;
cout << c[i].type << endl;
cout << c[i].selltype << endl;
cout << c[i].price << endl;
}
}
I have tried to find examples that specifically suit what I am trying to do but implementing them has not fixed the problem. Any help would be greatly appreciated.
The crux of the visible problem is that with
for (int i=0;i<100;i++)
the entire 100 element array will be printed out whether there was data in the file to be loaded into the array or not.
Probably the easiest way to do this is with a std::vector. It's a dynamically sized array. As you add to it it gets bigger so you don't have to worry about it overflowing. We'll get back to it at the end.
The next thing you have to do is make sure you're reading the file successfully. Streams can be tested to see if they are valid.
if (in)
{
cout << "in is good!" << endl;
}
and the >> operator returns a reference to the stream so you can
if (in >> data)
{
cout << "data is good!" << endl;
}
If the stream is still good after reading data, you know that at the very least the file read something into data that was of the correct type or could be converted into the correct type. You owe it to yourself to check the value read after reading it in to make sure the user didn't typo or go out of their way to crash the program. If you want to loop through a lot of stuff, like a file, you wind up with something like this:
while (in >> c[i].type >> c[i].selltype >> c[i].price)
If any of the reads failed the the stream will return false when tested and the loop will exit.
Looking at your source data you have spaces and commas to deal with. >> only knows how to deal with spaces unless you're going to do a lot of extra work. What you will read in is
knife,
object,
0
and we don't want the comma. Fortunately, it's the last character so dealing with it is easy. A C++11 std::string can be used like a stack and you can just pop the unwanted character off:
c[i].type.pop_back();
c[i].selltype.pop_back();
All together, this gives us a loop that looks like
ifstream in(filename);
itemlist c[100];
int i = 0;
while (in >> c[i].type >> c[i].selltype >> c[i].price)
{
c[i].type.pop_back();
c[i].selltype.pop_back();
cout << c[i].type << endl;
cout << c[i].selltype << endl;
cout << c[i].price << endl;
i++;
}
but this can overrun the end of the 100 element array, so we need to change the while loop slightly:
while (i < 100 && in >> c[i].type >> c[i].selltype >> c[i].price )
If i is greater than or equal to 100, the i < 100 case fails and the loop exits without even trying in >> c[i].type >> c[i].selltype >> c[i].price and writing into the non-existent array slot.
Remember to keep the value of i around because arrays are dumb. They don't know how full they are.
But with a vector you don't need i to count or to keep track of how full it is and you don't need to worry about overflowing the array until you run your computer out of RAM. What we do need is one temporary variable to read into and we're good to go.
vector<itemlist> c;
itemlist temp;
while (in >> temp.type >> temp.selltype >> temp.price)
{
temp.type.pop_back();
temp.selltype.pop_back();
cout << temp.type << endl;
cout << temp.selltype << endl;
cout << temp.price << endl;
c.push_back(temp);
}
I had the same problem.
A debug showed that it was reading the first array element but skipping to the second element and outputting the info. from the first element.
This was fixed by making it read the first element twice.
For example see below.
I had other input in the array for the player also.
After that line was added everything worked great.
I had to do that for every array that I read.
I looked at the text file it was reading from and sure enough
there is a blank line before the start of every array.
I do not know why the program writing the file did that.
I did not put a blank line before the array.
Note: Instead of having it read the first array element twice,
you could probably have it read a blank line instead.
for (int i = 0; i < PLAYER; i++)
{
getline(teamRosterIn, playerName[i]);
cout << playerName[i] << endl;
getline(teamRosterIn, playerName[i]);
cout << playerName[i] << endl;
}

Why is this code exiting at this point?

I'm new to C++. I stumbled upon one tutorial problem, and I thought I'd use the few things I have learnt to solve it. I have written the code to an extent but the code exits at a point, and I really can't figure out why. I do not want to go into details about the tutorial question because I actually wish to continue with it based on how I understood it from the start, and I know prospective answerers might want to change that. The code is explanatory, I have just written few lines.
Here comes the code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double average_each_student() {
cout << "\n>Enter your scores seperated by spaces and terminated with a period\n"
<< ">Note: scores after total number of six will be truncated.\n"
<< endl;
double sum = 0, average = 0;
int user_input, counter = 0;
const double no_of_exams = 6;
while(cin >> user_input) {
++counter;
if(counter < 5) sum += 0.15 * user_input;
else if(counter > 4 && counter < 7) sum += 0.20 * user_input;
}
return sum / no_of_exams;
}
int reg_number() {
cout << "Enter your registration number: " << endl;
int reg_numb;
cin >> reg_numb;
return reg_numb;
}
int main() {
vector<int> reg_num_list;
vector<double> student_average;
reg_num_list.push_back(reg_number());
student_average.push_back(average_each_student());
string answer;
cout << "\n\nIs that all??" << endl;
//everything ends at this point.
//process returns 0
cin >> answer;
cout << answer;
}
The code exits at cout << "\n\nIs that all??" << endl;. The rest part after that is not what I intend doing, but I'm just using that part to understand what's happening around there.
PS: I know there are other ways to improve the whole thing, but I'm writing the code based on my present knowledge and I wish to maintain the idea I'm currently implementing. I would appreciate if that doesn't change for now. I only need to know what I'm not doing right that is making the code end at that point.
The loop inside average_each_student() runs until further input for data fails and std::cin gets into failure state (i.e., it gets std::ios_base::failbit set).
As a result, input in main() immediately fails and the output of what was input just prints the unchanged string. That is, your perception of the program existing prior to the input is actually wrong: it just doesn't wait for input on a stream in fail state. Since your output doesn't add anything recognizable the output appears to do nothing although it actually prints an empty string. You can easily verify this claim by adding something, e.g.
std::cout << "read '" << answer << "'\n";
Whether it is possible to recover from the fail state on the input stream depends on how it failed. If you enter number until you indicate stream termination (using Ctrl-D or Ctrl-Z on the terminal depending on what kind of system you are using), there isn't any way to recover. If you terminate the input entering a non-number, you can use
std::cin.clear();
To clear the stream's failure stated. You might want to ignore entered characters using
std::cin.ignore(); // ignore the next character
or
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// ignore everything up to the end of the line
use cin.clear(); before cin >> answer; That will fix the problem. But you are not controlling the input. it just runs out to cin..

String to ascii function

I actually wrote a function to convert string into ascii values.
However I managed to confuse my self and don't understand why my own code works.
here it is:
void convertToString()
{
char redo;
int letter;
int length;
do {
cout<< "How long is your word \n";
cin >> length;
cout << "Type in the letter values \n";
for (int x = 0; x < length; x++) {
cin >> letter;
cout << char (letter);
}
cout << "\n To enter another word hit R" << endl;
cin >> redo;
} while (redo == 'R');
}
In the terminal I can type in all the ASCII values I want with out changing line, however I though this would cause a problem, anyways my question is, is hitting the enter button the same as hitting space? if not i dont understand how my code is able to print out the chars since i write it all in one line...Does it assign the interger "letter" a new value everytime there is a space?
Please help/explain
This is to expand a bit on what Igor said in his comment and to give a little example.
As Igor said, istream::operator>>(&int) will read non-whitespace. This means for each call on the operator, it scans along the input stream (what you typed in) for non-whitespace and reads until the next whitespace again. The next call will pick up where you left off. So, entering a space or a newline is exactly the same for this situation where you're taking in an int.
You can verify this with a simple bit of code that scans until EOF:
#include <iostream>
int main()
{
int number;
while (std::cin >> number)
{
std::cout << number << std::endl;
}
return 0;
}
This will wait for user entry to be complete (pressing enter), but print a new line for each integer in your input as separated by whitespace. So "1 2 3 4" will print each of those numbers on separate lines, regardless of if you separate them with spaces, tabs, or newlines.

ifstream not reading values from file in C++

I'm a novice user to C++ currently taking college courses in CS, and I'm stuck since my code does not read values from my input file, "OH-in.dat". Moreover, I don't quite know what to do when it comes to a sentinel value (since I require a do while loop, I think I'll just have to make the sentinel value be the first value I take and simply stop the loop from then on.)
Here's the code I have so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// Declare the variables to be used in the program.
ifstream infile;
string schoolname, location;
int tuition, enrollnum, i;
double average;
//Obtain the values for the variables from the file given.
infile.open("OH-in.dat"); //Accomplish task 1.
{
i = 0;
cout << "Schools in Cincinnati with tuition below $20,000." << endl;
cout << "-----------------------------------------------------" << endl;
do
{
// Read the values in the data file.
infile >> schoolname;
infile >> location;
infile >> enrollnum;
infile >> tuition;
// Separate the values that contain Cincinnati and if it's tuition is over 20000 dollars.
if (schoolname == "Cincinnati" && tuition < 20000)
{
cout << schoolname << " $" << tuition << endl;
i++;
}
// Display the number of schools that fit the criteria.
cout << "Number of schools: " << i << endl;
}
//While the 1st value read in is not ***, the loop will continue.
while (schoolname != "***");
//Close the file.
infile.close();
}
system("pause");
return 0;
}
Here's the first four values I will be inputting.
AntiochCollege
YellowSprings
330
27800
...
Finally, it will come to this.
'* * *'
This data was collected from petersons.com
on October 10 and 11. Some name and location
data has been altered.
Now, the main two problems I've had with this code have been simply getting C++ to read in the values and secondly getting the code to not infinitely repeat itself.
You can use something like
if (infile.fail()) break;
immediately after the four "infile >>" statements. Or you can use .eof() rather than .fail() if you like. Either way, it will exit your loop when infile has no more data to give.
In your specific case, of course, you're looking for the sentinel rather than the file's end, but the same principle applies. This is an ideal case for C++'s break statement.
Incidentally, once you add the break, you probably won't want the do-while any longer. A while(true) or for(;;) -- that is, a loop whose condition always passes -- will probably serve. This loop's natural exit point is in the middle, at the break you will add to it.

Ignore Spaces Using getline in C++ [duplicate]

This question already has answers here:
Need help with getline() [duplicate]
(7 answers)
Closed 7 years ago.
Hey, I'm trying to write a program that will accept new tasks from people, add it to a stack, be able to display the task, be able to save that stack to a text file, and then read the text file. The issue comes when I am trying to accept input from the user, whenever you enter a string with a space in it, the menu to choose what to do just loops. I need a way to fix this. Any help would be greatly appreciated.
// basic file io operations
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;
int main () {
//Declare the stack
stack<string> list;
//Begin the loop for the menu
string inputLine;
cout << "Welcome to the to-do list!" << endl;
//Trying to read the file
ifstream myfile ("to-do.txt");
if(myfile.is_open()){
//read every line of the to-do list and add it to the stack
while(myfile.good()){
getline(myfile,inputLine);
list.push(inputLine);
}
myfile.close();
cout << "File read successfully!" << endl;
} else {
cout << "There was no file to load... creating a blank stack." << endl;
}
int option;
//while we dont want to quit
while(true){
//display the options for the program
cout << endl << "What would you like to do?" << endl;
cout << "1. View the current tasks on the stack." << endl;
cout << "2. Remove the top task in the stack." << endl;
cout << "3. Add a new task to the stack." << endl;
cout << "4. Save the current task to a file." << endl;
cout << "5. Exit." << endl << endl;
//get the input from the user
cin >> option;
//use the option to do the necessary task
if(option < 6 && option > 0){
if(option == 1){
//create a buffer list to display all
stack<string> buff = list;
cout << endl;
//print out the stack
while(!buff.empty()){
cout << buff.top() << endl;
buff.pop();
}
}else if (option == 2){
list.pop();
}else if (option == 3){
//make a string to hold the input
string task;
cout << endl << "Enter the task that you would like to add:" << endl;
getline(cin, task); // THIS IS WHERE THE ISSUE COMES IN
cin.ignore();
//add the string
list.push(task);
cout << endl;
}else if (option == 4){
//write the stack to the file
stack<string> buff = list;
ofstream myfile ("to-do.txt");
if (myfile.is_open()){
while(!buff.empty()){
myfile << buff.top();
buff.pop();
if(!buff.empty()){
myfile << endl;
}
}
}
myfile.close();
}else{
cout << "Thank you! And Goodbye!" << endl;
break;
}
} else {
cout << "Enter a proper number!" << endl;
}
}
}
You have to add cin.ignore() right after options is chosen:
//get the input from the user
cin >> option;
cin.ignore();
And cin.ignore() is not necessary after your getline:
getline(cin, task); // THIS IS WHERE THE ISSUE COMES IN
//cin.ignore();
The problem is in options - if you didn't call cin.ignore() after it, options will contain end of line and loop will continue...
I hope this helps.
Don't do this:
while(myfile.good())
{
getline(myfile,inputLine);
list.push(inputLine);
}
The EOF flag is not set until you try and read past the EOF. The last full line read read up-to (bit not past) the EOF. So if you have have zero input left myfile.good() is true and the loop is enetered. You then try and read a line and it will fail but you still do the push.
The standard way of reading all the lines in a file is:
while(getline(myfile,inputLine))
{
list.push(inputLine);
}
This way the loop is only entered if the file contained data.
Your other problem seems to stem from the fact that you have:
std::getline(std::cin,task); // THIS is OK
std::cin.ignore(); // You are ignoring the next character the user inputs.
// This probably means the next command number.
// This means that the next read of a number will fail
// This means that std::cin will go into a bad state
// This means no more input is actually read.
So just drop the cin.ignore() line and everything will work.
Instead of using ">>" directly on your stream you might consider using getline and then attempting to fetch your option from that. Yes, it's less "efficient" but efficiency isn't generally an issue in such situations.
You see, the problem is that the user could enter something silly here. For example, they could enter something like "two", hit enter, and then your program is going to pitch a fit as it happily continues trying to decipher an empty option over and over and over and over again. The user's only recourse the way you have it set up (and the way those recommending use of ignore() are recommending) is to kill your program. A well behaved program doesn't respond in this way to bad input.
Thus your best option is not to write brittle code that can seriously break down with the most modest of user ignorance/malfunction, but to write code that can handle error conditions gracefully. You can't do that by hoping the user enters a number and then a newline. Invariably, someday, you'll bet poorly.
So, you have two options to read your option. First, read a full line from the user, make sure the stream is still good, and then turn the string you get into a stream and try to read your integer out of it, making sure this other stream is still good. Second option, attempt to read a number, verify that the stream is still good, read a line and make sure the stream is still good and that your string is empty (or just ignore it if it isn't, your choice).
#Vladimir is right. Here is the mechanism behind the bug:
When you enter option '3', what you actually put into stream is "3\n". cin >> option consumes "3" and leaves "\n". getline() consumes "\n" and your call to ignore() after getline() waits for user input.
As you can see, teh sequence of events is already not what you expected.
Now, while ignore() is waiting for input, you type in your line. That line you're typing is what will go to "cin >> option.
If you just give it one symbol, ignore() will dispose of it for you, and option will be read correctly. However, if you give it non-numeric symbols, stream will set failbit when trying to read the option. From that point on, your stream will refuse to do anything. Any << or getline will not set any new values in the variables they are supposed to change. You'll keep 3 in option and "" in task, in a tight loop.
Things to do:
always check cin.eof(), cin.fail() and cin.bad().
always initialize your variables and declare them in the narrowest scope possible (declare option=0 right before it's read).
I just figured out a way to kind of hack through it, not the greatest but it works. Create a character array, and then accept input in the array, and then put everything into the array into the string.
char buff[256];
cout << endl << "Enter the task that you would like to add:" << endl;
cin >> task;
task += " ";
cin.getline(buff, 256);
for(int i = 1; buff[i] != 0; i++){
task += buff[i];
}