This is for a homework assignment, but what I am presenting is a small test program for a chunk of my assignment.
Starting out, I am to have a list of songs in file "songs.txt". My current file looks like this.
Maneater;4;32
Whip It;2;41
Wake Me Up Before You Go-Go;3;45
The file simply contains a song title, and the duration in minutes and seconds, with the title, minutes, and seconds separated by semicolons. The full file is supposed to contain the Artists and Album as well, all separated by semicolons. Anyways, the code.
#include<iostream>
#include<cstring>
#include<fstream>
#include<cstdlib>
using namespace std;
const int CAP = 100;
const int MAXCHAR = 101;
struct songInfo
{
char title[CAP];
char durMin[CAP];
char durSec[CAP];
};
void getData(songInfo Song[], int listSize, int charSize);
int main()
{
string fileName;
songInfo Song[CAP];
ifstream inFile;
cout << "What is the file location?: ";
cin >> fileName;
inFile.open(fileName.c_str());
if (inFile.fail())
{
cout << "Cannot open file " << fileName << endl;
exit(1);
}
getData(Song, CAP, MAXCHAR);
for (int i=0;i<CAP;i++)
{
cout << Song[i].title << " - "
<< Song[i].durMin << ":"
<< Song[i].durSec << endl;
}
cout << "Press any button to continue..." << endl;
cin.get(); cin.get();
return 0;
}
void getData(songInfo Song[], int listSize, int charSize)
{
for (int i = 0; i < listSize; i++)
{
cin.get(Song[i].title, charSize, ';');
cin.get(Song[i].durMin, charSize, ';');
cin.get(Song[i].durSec, charSize, '\n');
i++;
cin.ignore();
}
}
The program compiles correctly without incident, but the output is not what I want it to be. What should happen:
Test.cpp opens songs.txt
Read the first char array into Song[i].title, delimited by ';'
Read the second char into Song[i].durMin, delimited by ';'
Read the third char into Song[i].durSec, delimited by newline
After compiling the code and running it, I get this as my output:
~/project2Test> ./test
What is the file location?: songs.txt
The program then hangs here and I have to ctrl+C out
First, what am I doing wrong?
Second, how do I go about fixing what I screwed up?
Also, as a note for class rules, I am not allowed to use any strings except for the filename. Other than that, all words must be chars.
A debugger is definitely a good thing to use for a problem like this.
Your hanging problem is occurring because in your get_data function you are using cin.get instructing your program to get input from the standard input file. You intended to use the file you defined, "inFile" not the standard input cin.
As an aside it is not clear to me why you are incrementing i twice per iteration of the for loop.
Use inFile.get() instead of cin. You need to pass inFile to the function first.
Put a print statement in the for loop to see what is happening.. A future issue that might crop up is that if you are on a Windows machine and have \r\n line endings. Unix uses \n, Windows uses \r\n
Related
I am trying to create a program in C++ using Microsoft Visual Studio 2013. The main purpose of this program is to read three different files(headlines1,headlines2, and headlines3) and put them all together to form a single file and creating a sentence within that output file. I have figured out a function that I could use, but this function only reads and prints the 3 files out onto the console window. When I try to change the cout statement into an outfile, my outfile that I created is blank... I don't know what to do or how to structure the code.
#include<fstream>
#include<iostream>
#include<cstdlib>
using namespace std;
void readingFile(string[], ifstream &); //Funtion Prototype
int main()
{
string header1[50], header2[50], header3[50]; //Declaring array with 50 elements
int size1, size2, size3;
ifstream Fin, Fin2, Fin3;
ofstream Fout;
Fin.open("Headlines1.txt"); //Reading from these 3 files.
Fin2.open("Headlines2.txt");
Fin3.open("Headlines3.txt");
if (!Fin || !Fin2 || !Fin3) //Checking for unsuccessful open
{
cout << "Input file opening failed.\n";
cin.ignore();
return 1;
}
Fout.open("testingHeadlines.txt"); //Used for unsuccessful opening output
if (!Fout)
{
cout << "Output file opening failed.\n";
cin.ignore();
return 2;
}
cout << "Building.... Editing....\n" << endl;
cin.ignore();
cout << "Headlines file 1 below:\n" << endl;
readingFile(header1, Fin); //Function call
cout << endl << endl;
cout << "Headlines file 2 below:\n" << endl;
readingFile(header2, Fin2); //Function call
cout << endl << endl;
cout << "Headlines file 3 below:\n" << endl;
readingFile(header3, Fin3); //Function call
cout << endl << endl;
cin.ignore();
return 0;
}
//the function 'readingFile'
//Pre-conditions: Reads the contents from the files of Headlines1,2,and 3
//Post-conditions: Prints out the contents.
void readingFile(string[], ifstream &infile)
{
char next;
infile.get(next);
while (!infile.eof()) //Reading until EndOfFile
{
cout << next; //Problem is here?? I would think.
infile.get(next);
}
}
I'm just not certain if where I said the "Problem is here??" is where the problem is at. Every time I change the cout to outfile(I know, I have to change the parameters within the function header) once doing that I open the outfile and the file is blank.
All the files contain random words/phrases and when put together they will make a sentence. For ex. Headlines1 contains '***Queen Jennifer*'** Headlines2 contains '***has brain surgery*'** Headlines3 contains '***after eating 30 jalapenos.*'** and When put together it should read 'Queen Jennifer has brain surgery after eating 30 jalapenos.' but the files contain more words/ phrases that what I just listed in my example.
When I run the program above I am able to read all three Headline files, but they are printed in up to down form. For example, my output on my console screen would be:
Queen
Jennifer
has brain surgery
after eating 30 jalapenos
Problem:
Getting my headlines to read from left to right.
Getting them into a output file instead of the console screen.
Help Please.
You could replace this...
void readingFile(string[], ifstream &infile)
{
char next;
infile.get(next);
while (!infile.eof()) //Reading until EndOfFile
{
cout << next; //Problem is here?? I would think.
infile.get(next);
}
}
...and the calls there-to, such as...
readingFile(header1, Fin);
...with this...
void readingFile(ifstream& infile, ofstream& fout)
{
char next;
while (infile.get(next)) //Reading until EndOfFile or error
if (next != '\n') // if not newline
fout << next; // stream to file
}
...and calls ala...
readingFile(Fin, Fout);
That way readingFile is told where to write the output, and filters out the newline characters that were causing the output to appear on different lines.
This should do the trick.
#include <fstream>
#include <string>
int main() {
// Open the three files.
std::ifstream file_1("Headlines1.txt");
std::ifstream file_2("Headlines2.txt");
std::ifstream file_3("Headlines3.txt");
// Combine into one string.
std::string content;
content += std::string(std::istreambuf_iterator<char>(file_1),
std::istreambuf_iterator<char>());
content += std::string(std::istreambuf_iterator<char>(file_2),
std::istreambuf_iterator<char>());
content += std::string(std::istreambuf_iterator<char>(file_3),
std::istreambuf_iterator<char>());
// Output the string into a single file.
std::ofstream output_file("testingHeadlines.txt");
output_file << content;
}
I'm not sure what you're wanting to do about spacing between files, but that shouldn't be too hard for you to fine-tune this code for.
one possible thing why your ouput is like this is that std::ifstream::get() that you used in infile.get(next) is a non-formatted reading method which means it will not skip white spaces and newline character \n by default. so you need to check if next value is a newline like this:
if(next == '\n') continue ;
before passing it to cout << next. Thus you will skip printing a newline in your console screen.
I'm pretty sure that this is a common question, but I can't find an example similar to mine, so..
I have a text file called input.txt that has: 0.0001234 1.0005434 0.0005678 1.0023423 0.00063452 1.0001546 0.00074321 1.00017654 in it.
Now I want to write a program to read that into an array, and then quickly check that it worked. So far, I've got:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
double PA[8];
int n;
ifstream myfile ("input.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << PA[line]<< endl;
}
myfile.close();
}
else cout << "Unable to open file";
for (n=0; n<8; n++) // to print the array, to check my work
{
cout << " {" << PA[n] << "} ";
}
system("PAUSE");
return 0;
}
My problem so far is that I keep getting the error: line was not declared. And I want to use the array later with floats to calculate new data. I think I'm doing it wrong for that.. Any help? Thanks!
declare line variable
int n, line = 0;
std::string value;
proper load data:
getline (myfile,value);
PA[line] = atof(value.c_str());
cout << PA[line]<< endl;
line++;
the variable line here
cout << PA[line]<< endl;
is not declared. and if you declare it, you also have to give it a value, otherwise it's undefined and the PA[line] is undefined, in other words: will crash.
the entire while block seems suspicious:
while (! myfile.eof() )
{
getline (myfile,line);
cout << PA[line]<< endl;
}
are you sure about the getline call?
I know a getline with this signature:
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
and that does not even match the number of arguments in your version.
if your input file has more than 8 lines on input, than the while loop will have that many interations - and your array has only space for 8 elements.
You need to declare the variable you called 'line' as follows:
int i=0;
while (! myfile.eof() && i<8)
{
std::string line; // this was the missing statement
getline (myfile,line);
double value = atof(line.c_str()); // convert line form char* to double
PA[i++] = value;
cout << value << endl;
}
Note that you need to convert line as double and use increment variable 'i' (for example, as I did. Make sure not overflowing PA capacity by checking i agains the size (currently 8, which should not hard coded, btw).
Also note that you shouldn't print the result if file access failed.
I'm just learning about text file input/output. I have outputted a file which contains a header and 10 rows of data underneath it.
I now want to read this back to the main function. This works for me if I leave out the header in the text file, but if I leave the header in, I get an infinite loop.
How can I skip the 1st line (the header line) in reading this data back, or if possible, read back the header as well as the data?
Here is what I have so far:
void fileRead(int x2[], double y2[], int& n, char filename)
{
ifstream fin ("pendulum.txt"); // fin is an input file stream
if(!fin) //same as fin.fail()
{
cerr << "Failure to open pendulum.txt for input" << endl;
exit(1);
}
int j = 0, dummy = 0; //index of the first value j and dummy value
while(!fin.eof()) //loop while not end of file
{
fin >> dummy >> x2[j] >> y2[j];
cout << setw(5) << fixed << j
<< setw(12) << scientific << x2[j] << " "
<< setw(12) << y2[j] << endl; //print a copy on screen
j += 1;
}
fin.close(); //close the input file
}
You can first read the header of the file then the real contents you want as follows:
string line;
getline(fin, line);//just skip the line contents if you do not want header
while (fin >> dummy >> x2[j] >> y2[j] )
{ //^^if you do not always have a dummy at the beginning of line
//you can remove dummy when you read the rest of the file
//do something
}
Your best bet would be to use
fin.ignore(10000,'\n');
http://www.cplusplus.com/reference/istream/istream/ignore/
This will ignore the first 10000 character in the file, or ignore the characters until a newline is reached. The 10000 is fairly arbitrary and should be a number that will always be longer than the maximum line length.
man, this gentleman over there helped me quite a lot. You see, everyone says to use getline(); to skip one line, but the problem is that sometimes you dont want to store anything in a buffer, so ignore() makes much more sense to me. Well so I would like to back up our fella's answer by adding that, you could use " numeric_limits::max()" which will make it have no limit, it will ignore until it finds the delimiter...
`
#include <iostream>
#include <fstream>
#include <limits>
using std::streamsize;
int main() {
ifstream fin ("pendulum.txt");
fin.ignore(numeric_limits<streamsize>::max(),'\n');
}
`
http://www.cplusplus.com/reference/limits/numeric_limits/
I wrote the code below that successfully gets a random line from a file; however, I need to be able to modify one of the lines, so I need to be able to get the line character by character.
How can I change my code to do this?
Use std::istream::get instead of std::getline. Just read your string character by character until you reach \n, EOF or other errors. I also recommend you read the full std::istream reference.
Good luck with your homework!
UPDATE:
OK, I don't think an example will hurt. Here is how I'd do it if I were you:
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
static std::string
answer (const string & question)
{
std::string answer;
const string filename = "answerfile.txt";
ifstream file (filename.c_str ());
if (!file)
{
cerr << "Can't open '" << filename << "' file.\n";
exit (1);
}
for (int i = 0, r = rand () % 5; i <= r; ++i)
{
answer.clear ();
char c;
while (file.get (c).good () && c != '\n')
{
if (c == 'i') c = 'I'; // Replace character? :)
answer.append (1, c);
}
}
return answer;
}
int
main ()
{
srand (time (NULL));
string question;
cout << "Please enter a question: " << flush;
cin >> question;
cout << answer (question) << endl;
}
... the only thing is that I have no idea why do you need to read string char by char in order to modify it. You can modify std::string object, which is even easier. Let's say you want to replace "I think" with "what if"? You might be better off reading more about
std::string and using find, erase, replace etc.
UPDATE 2:
What happens with your latest code is simply this - you open a file, then you get its content character by character until you reach newline (\n). So in either case you will end up reading the first line and then your do-while loop will terminate. If you look into my example, I did while loop that reads line until \n inside a for loop. So that is basically what you should do - repeat your do-while loop for as many times as many lines you want/can get from that file. For example, something like this will read you two lines:
for (int i = 1; i <= 2; ++i)
{
do
{
answerfile.get (answer);
cout << answer << " (from line " << i << ")\n";
}
while (answer != '\n');
}
This is a very strange issue. I'm trying to print a large text file, it's a Wikipedia entry. It happens to be the page on Velocity. So, when I tell it to print the file, it prints "In", when it should print "In physics, velocity is etc, etc etc".
Here's the code I'm using to print out:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream wiki;
wiki.open("./wiki/velocity.txt");
char* wikiRead;
wiki >> wikiRead;
cout << wikiRead << endl;
wiki.close();
}
Please help.
wiki >> wikiRead;
The default delimiter for stream is space, so when the stream encounters a space, it simply stops reading, that is why it reads only one word.
If you want the stream to read all words, the you've to use a loop as:
char* wikiRead = new char[1024]; //must allocate some memory!
while(wiki >> wikiRead)
{
cout << wikiRead << endl;
}
wiki.close();
delete []wikiRead; //must deallocate the memory
This will print all the words in the file, each on a new line. Note if any of the word in the file is more than 1024 character long, then this program would invoke undefined behavior, and the program might crash. In that case, you've to allocate a bigger chunk of memory.
But why use char* in the first place? In C++, you've better choice: Use std::string.
#include<string>
std::string word;
while(wiki >> word)
{
cout << word << endl;
}
wiki.close();
Its better now.
If you want to read line-by-line, instead of word-by-word, then use std::getline as:
std::string line;
while(std::getline(wiki, line))
{
cout << line << endl;
}
wiki.close();
This will read a complete line, even if the line contains spaces between the words, and will print each line a newline.
You ask the stream to read the (binary) value of a pointer (probably 4 bytes, depending on your machine architecture), then you ask it to print the text pointed to by those 4 bytes!
I wonder why you ignored the compiler warning (most of the modern compiler warns you about using uninitialized variables). How about this?
ifstream wiki;
wiki.open("./wiki/velocity.txt");
char wikiRead[255];
wiki >> wikiRead;
cout << wikiRead << endl;
wiki.close();
Alternatively I'd suggest you to use string object with getline to get a single line of text.
string str;
getline(wiki, str);
The >> operator applied to a char * reads only one word. Moreover, you're reading into an uninitialized pointer, which is not valid. Usually std::string, not char *, is used for string processing in C++.
If you only want to print the file's contents, you can hook the file's buffer directly to std::cout:
int main() {
std::ifstream wiki("./wiki/velocity.txt");
std::cout << wiki.rdbuf() << '\n';
}
If you want to put the contents into an automatically-allocated string, use std::getline with the delimiter disabled.
int main() {
std::ifstream wiki("./wiki/velocity.txt");
std::string wiki_contents;
getline( wiki, wiki_contents, '\0' /* do not stop at newline */ );
std::cout << wiki_contents << '\n'; // do something with the string
}
Since you want to read a large file, reading it block by block is a better way.
ifstream wiki;
wiki.open("./wiki/velocity.txt");
const int buf_size = 1024;
char* wikiRead = 0;
int cnt = 1;
do
{
wikiRead = realloc( wikiRead, bufsize*cnt );
wiki.Read( wikiRead + (bufSize*(cnt-1)), buf_size ); //appends to reallocated memory
cnt++;
}while( !wiki.eof())
wikiRead[(bufSize*(cnt-2)) + wiki.gcount() + 1] = '\0'; // null termination.
wiki.Close();
cout << wikiRead;
delete[] wikiRead;
The operator>> is designed to only read one word at a time. If you want to read lines, use getline.
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
int main()
{
ifstream wiki;
wiki.open("./wiki/velocity.txt");
string wikiRead;
while (getline(wiki, wikiRead))
{
cout << wikiRead << endl;
}
wiki.close();
}