Problem with getting text from a .txt file in c++ using fstream - c++

And thisI am trying to get the things written in a .txt file called CodeHere.txt and here is my main.cpp:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, const char * argv[]) {
string line;
string lines[100];
ifstream myfile ("CodeHere.txt");
int i = 0;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
lines[0] = line;
i++;
}
myfile.close();
}
else cout << "Unable to open file";
cout << lines[0];
myfile.close();
return 0;
}
And the output is: Writing this to a file.Program ended with exit code: 0
But in my CodeHere.txt it has: hello
I tried saving it, but the result didn't change. I'm not sure whats going on. Can anyone help?

Are you sure that your .txt file is in the same repertory? To me, it just looks like you entered the path wrong. Try with the absolute path (full one). Another option is that you haven't saved the text file yet, you're just editing it, and so it is in fact empty, that would be why your cout doesn't print anything.

This should work, using a vector<string> to store the lines read from file
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[]) {
string line;
vector<string> lines;
ifstream myfile ("CodeHere.txt");
int i = 0;
if (myfile.is_open())
{
while ( getline(myfile, line) )
{
lines.push_back(line);
i++;
}
myfile.close();
}
else {
cout << "Unable to open file";
return -1;
}
cout << lines[0] << '\n';
return 0;
}

Try this:
vector<string> lines;
if (file.is_open()) {
// read all lines from the file
std::string line;
while (getline(file, line)) {
lines.emplace_back(line);
}
file.close();
}
else {
cout << "Unable to open file";
return -1;
}
cout << "file has " << lines.size() << " lines." << endl;
for (auto l : lines) {
cout << l << endl;
}

Related

how to stop reading when i find end of line

i m trying to read from a file and stop when i hit end of line. the thing is, it doesnt seem to work.¯_(ツ)_/¯ any ideas why?
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char a;
ifstream myfile;
myfile.open("text.txt");
while (!myfile.eof())
{
myfile>> a;
if (a=='\n')
cout << "end of line";
}
myfile.close();
}
text file i read:
Try while (myfile.get(a)) instead?
while (myfile.get(a))
{
if (a=='\n')
cout << "end of line";
}
Why make things harder than needed. If you want to parse lines, then use std::getline().
#include <iostream>
#include <fstream>
int main(int argc, char *argv[]) {
std::ifstream myfile("text.txt");
std::string line;
while (std::getline(myfile, line)) {
std::cout << "end of line" << std::endl;
}
}
using a for loop
std::ifstream ifs( "file" );
for( char chr = 0; ifs.peek() != '\n'; ifs.get( chr ) ){
std::cout << chr;
}
ifs.close();
I just rewrite your code:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char a;
ifstream myfile;
myfile.open("/Users/sijan/CLionProjects/test2/text.txt",ifstream::in);
while (myfile.get(a))
{
cout<< a;
if (a=='\n')
cout << "end of line\n";
}
if (myfile.eof())
cout << "end of file";
myfile.close();
}

c++: Using a loop to open files

I have a vector of strings of 2 folder names vector <myClass> vec_fileNames; which I filled by reading from a fileNames.txt which contains 2 lines:
First
Second
ifstream inFile("c:/file names.txt");
if(!inFile)
{
cout << "File Not Found!\n";
inFile.close();
}
else
{
string line;
myClass class;
while (getline(inFile, line))
{
class.setFileName(line);
vec_fileNames.push_back(class);
}
So, at this point my vec_fileName[0].getFileName = First and vec_fileName[1].getFileName = second
Now I wanted to open files inside the folders who's names are in the vector in a loop so I did this:
for(int i = 0; i < vec_fileNames.size(); i++)
{
string fileName = vec_fileNames[i].getFileName();
ifstream inFile("C:/Program Folder\\" + fileName + "goalFile.txt");
if(!inFile)
{
cout << "File Not Found!\n";
inFile.close();
}
else
{
while (getline(inFile, line))
{
//do something
}
}
So far everything is good except for the file not being opened. Is this even something that can be done in c++ or is there an error in the way I'm opening the file?
I created the same folder structure as you have:
C:\
Program Folder
First
goalFile.txt
Second
goalFile.txt
And ran the following simple code. Node that I don't store the filenames in a class, but directly into a vector.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std; // I'm no fan of this, but you obviously used it.
void loadFileNames(vector<string>& vec_fileNames)
{
ifstream inFile("c:\\file names.txt");
if(!inFile.is_open())
{
cout << "File Not Found!\n";
return;
// inFile.close(); -- no need to close, it is not open!
}
else
{
string line;
while (getline(inFile, line))
{
cout << line << endl;
vec_fileNames.push_back(line);
}
}
}
void openFiles(vector<string>& vec_fileNames)
{
for(int i = 0; i < vec_fileNames.size(); i++)
{
string fileName = vec_fileNames[i];
string path("C:\\Program Folder\\" + fileName + "\\goalFile.txt");
ifstream inFile(path.c_str());
if(!inFile.is_open())
{
cout << "File" << vec_fileNames[i] << "Not Found!" << endl;
}
else
{
cout << "opened file in folder " << vec_fileNames[i] << endl << endl;
string line;
while (getline(inFile, line))
{
cout << line << endl;
}
cout << endl;
}
}
}
int main(int argc, char* argv[])
{
vector<string> fileNames;
loadFileNames(fileNames);
openFiles(fileNames);
return 0;
}
That works, and produces the output:
First
Second
opened file in folder First
First goal file 1
First goal file 2
opened file in folder Second
Second goalfile 1
Second goalfile 2
The lines First goal file 1, etc. are the contents of the two files.

How to append to one file, then copy said file into another file

I feel like I've tried everything, I can get the first file to append to the second but cannot get the second file into a third. What am I doing wrong?
To be clear I need to take one file, append it to a second file, then put the contents of that second file into a third. I was able to simulate this outcome by putting both files into strings and then putting those strings into a third file, but that's not 'correct' in this problem.
I'm not particular to any way or any technique, I've tried a few and nothing works. This is the latest attempt, still doesn't work for the last step.
Here's my code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string a,b,c;
cout << "Enter 3 file names: ";
cin >> a >> b >> c;
fstream inf;
ifstream two;
fstream outf;
string content = "";
string line = "";
int i;
string ch;
inf.open(a, ios::in | ios:: out | ios::app);
two.open(b);
outf.open(c, ios::in);
//check for errors
if (!inf)
{
cerr << "Error opening file" << endl;
exit(1);
}
if (!two)
{
cerr << "Error opening file" << endl;
exit(1);
}
if (!outf)
{
cerr << "Error opening file" << endl;
exit(1);
}
for(i=0; two.eof() != true; i++)
content += two.get();
i--;
content.erase(content.end()-1);
two.close();
inf << content;
inf.clear();
inf.swap(outf);
outf.close();
inf.close();
return 0;
Here's an idea:
#include <fstream>
using namespace std;
void appendf( const char* d, const char* s )
{
ofstream os( d, ios::app );
if ( ! os )
throw "could not open destination";
ifstream is( s );
if ( ! is )
throw "could not open source";
os << is.rdbuf();
}
int main()
{
try
{
appendf( "out.txt", "1.txt" );
return 0;
}
catch ( const char* x )
{
cout << x;
return -1;
}
}

Need help diagnosing errors in C++ program designed to extract timestamps from an XML file

With some help I've almost completed a program which enables me to extract the timestamps(eg:timestamp="2014-07-08T18:14:16.468Z" ) and only the timestamps from and XML file and output them to a designated output file. However, there are a handful of errors left in my code which have me at wits end, which can't seem to redress. Would someone more experienced with C++ mind helping me out?
The errors appear in lines 35,38, & 47.
Screenshot of errors: http://i.imgur.com/jVUig4T.jpg
Link to XML file: http://pastebin.com/DLVF0cXY
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
using namespace std;
string tempStr;
// escaped double qoute.
string findStr = "timestamp=\"";
ifstream inFile;
ofstream outFile;
outFile.open("Outputdata.txt");
inFile.open("Groupproject.xml");
if (inFile.fail()) {
cout << "Error Opening File" << endl;
system("pause");
exit(1);
}
size_t found;
while (inFile) {
getline(inFile, tempStr);
found = tempStr.find(findStr);
if (found != std::string::npos)
{
break;
}
}
// Erases from beggining to end of timestamp="
tempStr.erase(tempStr.begin(), (found + tempStr.length()));
// Finds index of next double qoute.
found = tempStr.findStr("\"");
if (found = std::string::npos)
{
cerr << "Could not find matching qoute:";
exit(1);
}
// Erases from matching qoute to the end of the string.
tempStr.erase(found, tempStr.end());
cout << "timestamp found" << tempStr << "Saving to outFile" << endl;
outFile << tempStr;
inFile.close();
outFile.close();
system("pause");
return 0;
}
Are you sure you carefully read the reference for all the functions you are using ? Your new friend
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
string tempStr;
string findStr = "timestamp=\""; // escaped double quote
ifstream inFile;
ofstream outFile;
outFile.open( "Outputdata.txt" );
inFile.open( "Groupproject.xml" );
if ( inFile.fail() )
{
cout << "Error Opening File" << endl;
cin.get();
exit( 1 );
}
size_t found;
while ( inFile )
{
getline( inFile, tempStr );
cout << tempStr << endl;
found = tempStr.find( findStr );
if ( found != string::npos )
break;
}
tempStr.erase( 0, found + findStr.length() ); // erases from beggining to end of timestamp="
found = tempStr.find( "\"" ); // finds index of next double quote
if ( found == string::npos )
{
cerr << "Could not find matching quote" << endl;
exit( 1 );
}
tempStr.erase( found, string::npos ); // erases from matching quote to the end of the string.
cout << "timestamp found:" << tempStr << " Saving to outFile" << endl;
outFile << tempStr;
inFile.close();
outFile.close();
cin.get();
return 0;
}

Passing a file into a function

I'm trying to create a program that passes a file to a function. The function is supposed to detect how many lines are in my file. I don't think I'm passing the file correctly into my function, I've tried several different ways. Any help will be greatly appreciated.
#include <iostream>
#include <fstream>
#define die(errmsg) {cerr << errmsg << endl; exit(1);}
using namespace std;
int num_of_lines(ifstream file)
{
int cnt3;
string str;
while(getline(file, str))cnt3++;
return(cnt3);
}
int main(int argc, char **argv)
{
int num_of_lines(ifstream file);
string file;
file = argv[1];
if(argc == 1)die("usage: mywc your_file"); //for some reason not working
ifstream ifs;
ifs.open(file);
if(ifs.is_open())
{
int a;
cout << "File was opened\n";
a = num_of_lines(file);
cout <<"Lines: " << a << endl;
}
else
{
cerr <<"Could not open: " << file << endl;
exit(1);
}
ifs.close();
return(0);
}
Two problems with the function. First, you should pass the stream by reference. Second, you just forgot to initialise your counter.
int num_of_lines( ifstream &file )
{
int cnt3 = 0;
string str;
while( getline(file, str) ) cnt3++;
return cnt3;
}
The other thing is you're passing file to it (which is a string) instead of ifs. Change the call to:
a = num_of_lines( ifs );