Inputting a file name and having the text read - c++

I want the user to enter the name of a file, and if the file exists, print out all the contents of the file.
At the moment the uncommented code, takes a name of a file that the user inputs, for example. example.txt and prints out most (not the last word?) of the file. I've tried to implement this instead by using string (commented code is attempt) but clearly its incorrect.
I also wondering if i can automatically add .txt to the end of the user input, so that the console could ask - "which subject should we find more information on" user inputs "math" and it will open "math.txt"
Here is what I´ve tried:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
char filename[50];
//string getcontent;
ifstream name;
cin.getline(filename, 50);
name.open(filename);
if (!name.is_open()) {
exit(EXIT_FAILURE);
}
char word[50];
name >> word;
while (name.good()) {
cout << word << " ";
name >> word;
}
//if (!name.is_open()) {
//while (! filename).eof())
//{
//getline(name, getcontent)
//cout << getcontent << endl;
//}
//exit(EXIT_FAILURE); //comes from cstdlib
//}
//}
system("pause");
return 0;
}

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
string filename;
string getcontent;
ifstream name;
cin >> filename;
filename.append(".txt"); // add extension.
name.open(filename);
if (!name.is_open()) {
exit(EXIT_FAILURE);
}
while (true)
{
getline(name, getcontent);
if (name.eof()) break;
cout << getcontent << endl;
}
return 0;
}

I found this and it helped me with a somewhat different problem and I also thought that I might be able to help. This is coded in windows. (I'm a beginner so forgive me if I made some obvious mistakes)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin;
int main()
{
//char filename[50],word[50];
string filename,word;
//cin.getline(filename,50);
getline(cin,filename);
//strcat(filename,".txt");
filename.append(".txt");
fin.open(filename);
if(fin.is_open())
while(fin>>word)
cout<<word<<endl;
else
cout<<"No such file"<<endl;
return 0;
}

Related

How do i compare two text files in c++

okay I've searched everywhere and couldn't get my hand on it so ..
i'm doing a library system where a librarian enters his username and the program checks if he is one of the librarians or not
i'm stuck on the comparing part , i tried using getline but it gave me an error , tried gets_s and used a char array instead of a string and still didn't work
kindly help me with what i should do
using namespace std;
#include <iostream>
#include <string>
#include <fstream>
int main()
{
//opening files
ifstream readUsername;
ofstream enterUsername;
//variables
string existUsername;
string enteredUsername;
//reading files
readUsername.open("librarian usernames.txt");
if (readUsername.fail())
{
cout << "can't open file" << endl;
}
enterUsername.open("entered librarian username.txt");
if (enterUsername.fail())
{
cout << "can't open file" << endl;
}
while(!readUsername.eof)
{
readUsername >> existUsername;
}
enterUsername << enteredUsername;
readUsername.close();
enterUsername.close();
enterUsername.clear();
system("pause");
return 0;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream infile;
infile.open("listOfWords.txt"); //open file
for(string listOfWords; getline(infile, listOfWords, '.'); ) //read sentences including
//spaces
cout<<listOfWords; //this displays
return 0;
}
This shows you how to output the text so you should just save both files to a variable then compare the variables.

Trying to open file and copy it word by word with vector

I'm trying to open a file and read it word by word. I can't figure out where my issue is as it seems to break down after opening the file.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <vector>
#include <array>
using namespace std;
int main()
{
string path, test;
ifstream inputFile;
vector<string> words;
cout << "What is the path for the input file? ";
getline(cin, path);
inputFile.open(path, ios::in);
while (!inputFile.eof())
{
cin >> test;
words.push_back(test);
}
for (int i = 0; i < words.size(); i++)
{
cout << words.at(i) << endl;
}
inputFile.close();
return 0;
}
while (!inputFile.eof())
{
cin >> test;
words.push_back(test);
}
There are two problems here:
You opened inputFile but then attempt to read from std::cin
"while (!inputFile.eof())" is always the wrong thing to do.
Well, there's also a third problem here:
Using a debugger would've immediately identified both problems. As an example, I loaded the compiled code in a debugger and stepped through it. The issues were readily apparent.
#Sam has all the things you did wrong.
But an alternative to using a loop is just to use iterators to build the array.
std::ifstream file(path);
std::vector<std::string> words(std::istream_iterator<std::string>(file),
std::istream_iterator<std::string>());
To print it out you can use copy.
std::copy(std::begin(words), std::end(words),
std::ostream_iterator(std::cout, "\n"));
Currently this will break words using white space as the separator between words. This means punctuation etc will be included with words. Look here on how to get the streams to treat punctuation as space: How to tokenzie (words) classifying punctuation as space
Thanks to everyone for the help. Here is the final code (for anyone who ends up Googling this in the future)
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <vector>
#include <array>
using namespace std;
int main()
{
string path, test;
ifstream inputFile;
vector<string> words;
cout << "What is the path for the input file? ";
getline(cin, path);
inputFile.open(path, ios::in);
while (inputFile >> test)
{
words.push_back(test);
}
for (int i = 0; i < words.size(); i++)
{
cout << words.at(i) << endl;
}
inputFile.close();
return 0;
}

How do I remove all the punctuation from the file that I am reading from?

This is my main method in a file called main.cpp:
#include <iostream>
#include "ReadWords.h"
#include "Writer.h"
#include <cctype>
#include <string>
using namespace std;
int main() {
int count;
int length;
string word;
cout << "Please enter a filename: " << flush;
char filename[30];
cin >> filename;
This is where I am trying to delete all the punctuation in the file. Currently I am able to read the file and print all the values. I am struggling to access the file and delete the punctuation. I know that I am to use ispunct. I have tried many different implementations but cannot get it to work. How do I delete all the punctuation in the file?
ReadWords reader(filename);
while (reader.isNextWord()){
count = count + 1;
reader.getNextWord();
}
cout << "There are: " << count << " words in this text file" << endl;
return 0;
}
This is another file called ReadWords where I have all my method declarations: I don't think this is relevant/needed
#include "ReadWords.h"
#include <cstring>
#include <iostream>
using namespace std;
void ReadWords::close(){
}
ReadWords::ReadWords(const char *filename) {
//storing user input to use as the filename
//string filename;
wordfile.open(filename);
if (!wordfile) {
cout << "could not open " << filename << endl;
exit(1);
}
}
string ReadWords::getNextWord() {
string n;
if(isNextWord()){
wordfile >> n;
return n;
}
}
bool ReadWords::isNextWord() {
if (wordfile.eof()) {
return false;
}
return true;
}
Read from the input file one character at a time.
For each character you read:
If the character is not punctuation, write it to the output file.
If the character is punctuation, don't write it to the output file.

Read text file display to console then append text file

I have a text file of names. I want to read the text file into a stream, display it to the console. When it is done, it will prompt the user to enter their name. It should then add it to the file.
I can get it to do both of these things separately but not together.
Here is my code.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
using namespace System;
int main(array<System::String ^> ^args)
{
fstream myfile;
string line;
string name;
myfile.open("Names.txt",ios::out | ios::in | ios_base::app);
if (myfile.is_open())
{
while( getline(myfile, line) )
{
cout << line << endl;
}
cout << "Enter your name!\n";
getline (cin, name);
myfile << name;
myfile.close();
}
else
{
cout << "file was not opened\n";
}
return 0;
}
If I leave the while loop in there, it writes all the names to the console, but doesn't append the user entered name to the list. If I take out the while loop, I can add a name to the file but then of course I am not getting a list of the names that are already in that file.
My best guess is, I think it might have something to do with the fact that after I loop through the file using getline, The position is at the end of my stream, so when I try to add a name to it, there isn't any room left in the stream?
Your guess is correct.
The last call to getline() (the one that failed) set the error flags on your stream, which will fail any further IO attempts, which is why nothing is actually written in your file.
You can reset the errors flags with clear() after your reading loop :
myfile.clear();
Note:
You should also test for the returned value of your last getline() call.
Just bumped in to this issue and even though there is accepted answer here I think one can use full code that shows how to use canonical C++ file reading loop:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
using namespace System;
int main(array<System::String ^> ^args)
{
fstream myfile;
string line;
string name;
myfile.open("Names.txt",ios::out | ios::in | ios_base::app);
if (myfile.is_open())
{
while( getline(myfile, line) )
cout << line << endl;
if (file_list.eof())
file_list.clear(); //otherwise we can't do any further I/O
else if (file_list.bad()) {
std::cout << "Error occured while reading file";
return 1;
}
cout << "Enter your name!\n";
getline (cin, name);
myfile << name;
myfile.close();
}
else
{
cout << "file was not opened\n";
}
return 0;
}

How to open any input file whether it contains words or numbers and prints it out. C++

So Lets say this is what the input file contains
12
Hello
45
54
100
Cheese
23
How would I print it out on the screen in that order.
This is what I had but it skips some lines.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int number;
string word;
int loop = 0;
ifstream infile;
infile.open("arraynumbers.txt");
while(infile >> number >> word)
{
if( infile >> number)
{
cout << number << endl;
}
if(infile >> word)
{
cout << word << endl;
}
}
return 0;
}
I suggest using www.cplusplus.com to answer these questions.
However, you are on the right track. Since you are just outputting the contents of the file to stdout, I suggest using readline() and a string. If you need to access the numeric strings as ints, use the atoi() function.
Example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream file("arraynumber.txt");
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else cout << "Error opening arraynumber.txt: File not found in current directory\n";
return 0;