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;
}
Related
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.
I am attempting to take a txt file and create a string from it but I cannot figure out how to make it work.
I have tried to use the getline string function but it does not create a proper string in the way I have used it.
ifstream inFile("somefile.txt");
string mystring;
while (getline(inFile, mystring)) {
cout << mystring << endl;
}
The end goal of my program is to read a .txt file line by line and edit each line so it is 100 char wide. This first part seems to be the only place where I am having an issue at the moment.
This can be due to the stream object could not find or open the file. Try checking if the inFile is good or valid.
#include <iostream>
#include <string>
#include <fstream>
using std::cout;
using std::ifstream;
using std::string;
using std::endl;
int main() {
ifstream inFile("example.txt");
string mystring;
if( inFile ) // or inFile.good()
{
while (getline(inFile, mystring))
{
cout << mystring << endl;
}
}
else
{
cout << "Could not open File\n";
}
return 0;
}
This is my first project in C++. I took a course using C previously and file I/O seems to differ a little.
The project requires the user to enter a name for saving the output file.
I know I should use ofstream which should look like this:
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
I've bolded the snippet that's causing confusion.
How can I name the file from a string entered by the user?
*Note, C type string, so an array of characters.
#include < string > is not allowed
As my other answer has got a negative vote, here's another solution without #include <string>
You can just save the input from the user in a temporary char array and then save it to a string variable std::string.
Includes that are necessary:
#include <iostream>
#include <fstream>
Saving an input from an user into a char array:
char input[260];
cin >> input;
To then save it in a string variable just do this:
string filename = input;
To open a file stream you'll need to use std::ofstream. Please keep in mind, that the file is created in the same folder as the project/application is.
std::ofstream outfile (filename + "." + "file extension");
And as you already know this outfile.open(); opens the file.
With outfile << "hello"; you can write into the file.
To close the file, use outfile.close(); to close the file.
Here you have a little example code:
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
char input[260];
cin >> input;
string filename = input;
ofstream outfile(filename + "." + "txt");
outfile << "hello";
outfile.close();
}
I hope this helps.
Regards.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string path;
string name;
string h_path;
string text;
void create() {
ofstream file(h_path, ios::app);
if (!file.fail()) {
file << text;
file.close();
}
}
int main() {
cout << "please enter path(c:\\folder\): ";
cin >> path;
cin.ignore();
path = path + "/";
cout << "please enter the name of the file (test.txt): ";
getline(cin, name);
cout << "content of the file: ";
getline(cin, text);
h_path = path + name;
create();
cout << "new file created";
cout << h_path;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string fileName;
cin >> fileName;
ofstream myfile;
myfile.open(fileName);
myfile << "Writing this to a file.\n";
myfile.close();
}
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;
}
I have this code that reads from marks.txt file.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main () {
string name,result;
int number1;
ifstream myfile ("marks.txt");
if (myfile.is_open())
{
while ( !myfile.eof() )
{
getline (myfile,name,'\t');
getline (myfile,result,'\t');
stringstream(result) >> number1;
cout << number1;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
with my marks.txt file consists of:
john 20
But when i ran the program. Number1 output is 36. How can i convert result string to int correctly??
Note that you're passing \t (tab character) as the delimiter to getline. Are you sure you are using a tab in your input file? If you use a space or any other character, all the input will go into name and your result will be empty, which will leave number1 undefined. I suspect that's the reason you're getting 36 out of nowhere.