I/O file stream C++ - c++

#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
using namespace std;
int main()
{
string temp;
ifstream inFile;
ofstream outFile;
inFile.open("ZRMK Matched - 010513.txt");
outFile.open("second.txt");
while(!inFile.eof()) {
getline(inFile, temp);
if (temp != "") {
getline(inFile, temp);
outFile << temp;
}
}
cout << "Data Transfer Finished" << endl;
return 0;
}
I'm having difficulty getting this to work. When I execute the program it cycles for awhile and then terminates without finishing -- it doesn't output any lines of text to the output file. Any help would be appreciated.

Are you trying to copy every line?
while(std::getline(inFile, temp)) {
outFile << temp << "\n";
}
Are you trying to copy every non-blank line?
while(std::getline(inFile, temp)) {
if(temp != "")
outFile << temp << "\n";
}
Are you trying to copy every 2nd non-blank line?
int count = 0;
while(std::getline(inFile, temp)) {
if(temp == "")
continue;
count++;
if(count % 2)
outFile << temp << "\n";
}
Are you simply trying to copy the entire file?
outFile << inFile.rdbuf();

You should use a mode to open files : see std::ios_base::openmode
And don't forget to close the streams you open !
You can even try catch your code to understand the problem if an exception occurred.
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
try {
fstream inFile;
fstream outFile;
// open to read
inFile.open("ZRMK Matched - 010513.txt", ios_base::in);
if (!inFile.is_open()) {
cerr << "inFile is not open ! " << endl;
return EXIT_FAILURE;
}
// Open to append
outFile.open("second.txt", ios_base::app);
if (!inFile.is_open()) {
cerr << "inFile is not open ! " << endl;
return EXIT_FAILURE;
}
string line;
while(getline(inFile, line)) {
if (!line.empty()) {
outFile << line << endl;
}
}
if (outFile.is_open()) {
outFile.close(); // Close the stream if it's open
}
if (inFile.is_open()) {
inFile.close(); // Close the stream if open
}
cout << "Data Transfer Finished" << endl;
return EXIT_SUCCESS;
} catch (const exception& e) {
cerr << "Exception occurred : " << e.what() << endl;
}
return EXIT_FAILURE;
}

Related

Reverse stack into file

I need to create a program that reads a file, pushes the content into a stack, then writes that content in reverse to another file. I don't understand why my file isn't being found or outputting. Here is my code:
#include "stdafx.h"
#include <iostream>
#include <stack>
#include <fstream>
#include <string>
int main() {
std::stack<char>charStack;
std::fstream file;
std::fstream revFile;
std::string fileName;
std::cout << "Enter the name of the file you want to open." << std::endl;
std::cin >> fileName;
file.open(fileName);
std::cout << "Adding input from file to stack." << std::endl;
char ch;
file >> std::noskipws;
while (file >> ch) {
std::cout << ch;
charStack.push(ch);
}
file.close();
revFile.open("newFile.txt");
std::cout << std::endl;
std::cout << "Reversing stack and writing to file." << std::endl;
while (!charStack.empty()) {
char i = charStack.top();
revFile << i;
charStack.pop();
}
revFile.close();
revFile.open("newFile.txt");
std::cout << "Here is the original file reversed." << std::endl;
std::string line;
if (revFile.is_open()) {
while (std::getline(revFile, line)) {
std::cout << line;
}
revFile.close();
}
else std::cout << "Unable to open file" << std::endl;
revFile.close();
return 0;
}
I'm unsure if I need to add an empty .txt file to write to or if this should generate one for me. Any help would be appreciated.
You need to change the file opening statements to be:
revFile.open("newFile.txt",ios::out); //for output
and
revFile.open("newFile.txt",ios::in); //for input
other than that, you just need to correct this line to get a correct printing of the file contents after reversing.
std::cout << line;
Make it:
std::cout << line << "\n";

Reading lines from file in C++

Why can't I get each line in a file printed with this? It outputs nothing.
string line;
ifstream s {"book_list.txt"};
while (getline(s, line)) {
cout << line << endl;
}
I've included fstream, sstream, string, stdio.h, stdlib.h and am using namespace std;
#include<iostream>
#include<fstream>
#include<string>
using namespace std
int main()
{
string line;
ifstream s ("book_list.txt");
if (s.is_open())
{
while ( getline (s,line) )
{
cout << line << endl;
}
s.close(); // Don't forget to close the file
}
else
cout << "Unable to open file";
return 0;
}
I hop it helps.
I guess the file doesnt exist.
Please check with:
if(!s.good()) {
// error
}
or
while (s.good()) {
// process.
}
You should do something like this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string sLine = "";
ifstream infile;
infile.open("temp.txt");
if(infile.is_open()){
while (getline(infile, sLine))
{
cout << sLine << endl;
}
}
infile.close();
cout << "Read file completed!!" << endl;
}
#include <iostream>
#include <fsstream>
using namespace std;
int main()
{
string data;
int counter = 0;
ifstream infile("test_file.txt");
while (!infile.eof()){
getline(infile , data);
counter += 1;
}
cout << "The number of lines is : " << counter << endl;
return 0;
}

ifstream ofstream on mac

I'm trying to read in a random file (on mac-xcode) and determine the instances of the letter k in the document. Then print the number as an outout file. My problem is that the outfile isn't being written and the nums_k is coming back as 0. I'm not sure if the ifstream is working incorrectly or the ofstream need a different filename established. Here's my source code.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream infile("Users/bryanmichaelnorris/documents/extra credit assignment.docx");
string line;
int numks = 0;
while (getline(infile,line)) {
int x = 0;
for (std::string::iterator it=line.begin(); it!=line.end(); ++it) {
if (line[x] == 'k') {
numks++;
}
x++;
}
}
infile.close();
ofstream outfile("number of k's.docx");
outfile << "There are " << numks << " K's in the file." << endl;
outfile.close();
return 0;
}
Added validations for the opened files.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const char * csInputFileNane="Users/bryanmichaelnorris/documents/extra credit assignment.docx";
ifstream infile(csInputFileNane);
if (!infile.is_open()) {
cerr << "Cannot open file \""<<csInputFileNane<<'"'<<endl;
return -1;
}
string line;
int numks = 0;
while (getline(infile,line))
{ int x = 0;
for (std::string::iterator it=line.begin(); it!=line.end(); ++it) {
if (line[x] == 'k')
{
numks++;
}
x++;
}
}
infile.close();
const char *csOutFileName="number of k's.docx";
ofstream outfile(csOutFileName);
if (!outfile.is_open()) {
cerr << "Cannot open file \""<<csOutFileName<<'"'<<endl;
return -1;
}
outfile << "There are " << numks << " K's in the file." << endl;
outfile.close();
return 0;
}

Reading "tokens" from a string line in C++ I/O

I am wondering how I can do the following in C++ since I am only familiar with Java.
I have a string which we will call line.
string line = "hello how are you";
In C++ I have retrieved that line from getLine(). I want to traverse through this line so I can count the number of words in this line. The result should be 4, in my example.
In Java, I would have imported Scanner. Then do something like this:
//Other scanner called fileName over the file
while(fileName.hasNextLine()) {
line = fileName.nextLine();
Scanner sc = new Scanner(line);
int count=0;
while(sc.hasNext()){
sc.next();
count++;
}
}
I am only using #include<iostream>, fstream and string.
You can use stringstream
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string line;
getline(cin,line);
stringstream ss(line);
string word;
int count=0;
while(ss>>word){//ss is used more like cin
count++;
}
cout<<count<<endl;
return 0;
}
http://ideone.com/Yl25KT
I would avoid ifstream::getline and just use ifstream::get instead. You don't even need to use string.
#include <iostream>
int main()
{
int numwords = 1; //starts at 1 because there will be (numspaces - 1) words.
char character;
std::ifstream file("readfrom.txt");
if (file.fail())
{
std::cout << "Failed to open file!" << std::endl;
std::cin.get();
return 0;
}
while (!file.eof())
{
file >> character;
if (character == ' ')
{
numwords++;
std::cout << std::endl;
}
else if (character == '\n') //endline code
{
std::cout << "End of line" << std::endl;
break;
}
else
std::cout << character;
}
std::cout << "Line contained " << numwords << " words." << std::endl;
std::cin.get(); //pause
return 0;
}

Checking if word exists in a text file c++

I need to check if a word exists in a dictionary text file, I think I could use strcmp, but I don't actually know how to get a line of text from the document. Here's my current code I'm stuck on.
#include "includes.h"
#include <string>
#include <fstream>
using namespace std;
bool CheckWord(char* str)
{
ifstream file("dictionary.txt");
while (getline(file,s)) {
if (false /* missing code */) {
return true;
}
}
return false;
}
std::string::find does the job.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool CheckWord(char* filename, char* search)
{
int offset;
string line;
ifstream Myfile;
Myfile.open (filename);
if (Myfile.is_open())
{
while (!Myfile.eof())
{
getline(Myfile,line);
if ((offset = line.find(search, 0)) != string::npos)
{
cout << "found '" << search << "' in '" << line << "'" << endl;
Myfile.close();
return true;
}
else
{
cout << "Not found" << endl;
}
}
Myfile.close();
}
else
cout << "Unable to open this file." << endl;
return false;
}
int main ()
{
CheckWord("dictionary.txt", "need");
return 0;
}
char aWord[50];
while (file.good()) {
file>>aWord;
if (file.good() && strcmp(aWord, wordToFind) == 0) {
//found word
}
}
You need to read words with the input operator.