this does create a file like i want but instead of the input name it just calls it fileName and it doesn't have a type. Its supposed to take an input of something like "story.txt" and create a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string userInput;
string endWrite = "** STOP **";
string fileName = "";
cin >> fileName;
ofstream storyTime(fileName.c_str());
storyTime.open("fileName");
if (!storyTime.is_open()) {
cout << "Could not open file " << fileName << "." << endl;
return 1;
}
getline(cin, userInput);
while (userInput != endWrite) {
storyTime << userInput << endl;
getline(cin, userInput);
}
storyTime.close();
return 0;
}
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
void wordCount(ifstream& in_stream, ofstream& out_stream);
int main()
{
char inputFile[100];
ifstream fin;
ofstream fout;
cout << "Enter a File name: " << endl;
cin >> inputFile;
fin.open(inputFile);
if (fin.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
wordCount(fin, fout);
fin.close();
fout.close();
return 0;
}
void wordCount(ifstream& in_stream, ofstream& out_stream)
{
int counter = 0,i;
char next,last[1];
in_stream.get(next);
while (!in_stream.eof())
{
if (next == ' ')
(next >> last[1]);
for(i = 0; last[i] != '\0'; ++i)
{
if (last[i] == ' ')
counter++;
}
in_stream.get(next);
}
}
I'm trying to get the word count of this and its not working
the chars being saved are fine, but whats not working if I input from notepad a file with something like:
I
am
working
it will show 0 words if I I type normally it will count the words why is that?
I edit your code, Do you mean something like this?
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int wordCount(ifstream& in_stream, ofstream& out_stream);
int main()
{
char inputFile[100];
ifstream fin;
ofstream fout;
cout << "Enter a File name: " << endl;
cin >> inputFile;
fin.open(inputFile);
if (fin.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
int WordCount = wordCount(fin, fout);
fin.close();
fout.close();
return 0;
}
int wordCount(ifstream& in_stream, ofstream& out_stream)
{
int counter = 0;
char data[100];
in_stream >> data;
while (strlen(data)>0)
{
counter++;
in_stream >> data;
}
return counter;
}
This is one of my homework and I keep running into seg fault after the cin while loop, can anybody tell what did I do wrong? I have not learn map yet so I can't do that. One of my thought is that it went into seg fault because I was comparing the two string elements inside the vector, what is the way to do that properly?
#include <chrono>
#include <climits>
#include <cfloat>
#include <limits>
#include <cassert>
#include <exception>
#include <cctype>
#include <string>
#include <cmath>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <regex>
#include <vector>
using namespace std;
int main()
{
vector<string> word_input;
vector<int> word_count;
string word;
string fileName;
ifstream inputFile;
cout << "Enter file name: ";
getline(cin,fileName);
inputFile.open(fileName);
while (inputFile.fail())
{
cout << "Can't open the file" << endl;
exit(1);
}
cout << "File opened successfully \n";
while (inputFile >> word)
{
if (word != word_input.back())
{
word_input.push_back(word);
word_count.push_back(1);
}
else
{
word_count.push_back( word_count.back() + 1);
}
}
int count =word_count.back();
// Compare the input words
// and output the times of every word compared only with all the words
for (int i = 0; i != count; ++i)
{
int time = 0;
for (int j = 0; j != count; ++j)
{
if (word_input[i] == word_input[j])
++time;
}
std::cout << "The time of "
<< word_input[i]
<< " is: "
<< time
<< endl;
}
inputFile.close();
return 0;
}
The strategy you are using is fraught with problems. A simpler approach would be to use a std::map<std::string, int>.
int main()
{
std::map<std::string, int> wordCount;
string word;
string fileName;
ifstream inputFile;
cout << "Enter file name: ";
getline(cin,fileName);
inputFile.open(fileName);
if (inputFile.fail())
{
cout << "Can't open the file" << endl;
exit(1);
}
cout << "File opened successfully \n";
while (inputFile >> word)
{
// --------------------------------------------------------------
// This is all you need to keep track of the count of the words
// --------------------------------------------------------------
wordCount[word]++;
}
for ( auto const& item : wordCount )
{
std::cout << "The time of "
<< item.first
<< " is: "
<< item.second
<< std::endl;
}
inputFile.close();
return 0;
}
Below code is able to send a single student information to a file at once. How can it modified to send more records one after another without exiting and re-opening the program. I'm new for this. Kindly help.
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <windows.h>
#include <sstream>
#include <algorithm>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <iomanip>
#include <dos.h>
using namespace std;
string userName;
string passWord;
string selection;
int option;
struct patientinfo {
string PatientFname;
string PatientLname;
int Age;
int ContactNo;
string TreatmentType;
string AppDate;
string AppTime;
int eReciptId;
};
int num;
patientinfo emp[50];
void makeBooking()
{
ofstream outputFile;
outputFile.open("smt.bin", std::ofstream::in | std::ofstream::out | std::ofstream::app);
int i=num;
num+=1;
cout<< endl << endl << endl << endl << endl << endl
<< setw(30)<<"First Name : ";
cin>>emp[i].PatientFname;
outputFile <<emp[i].PatientFname <<",";
cout<< setw(30)<<"Last Name : ";
cin>>emp[i].PatientLname;
outputFile <<emp[i].PatientLname <<",";
cout<< setw(30)<<"Age : ";
cin>>emp[i].Age;
outputFile <<emp[i].Age <<",";
}
int main ()
{
makeBooking();
return 0;
}
Considering you have 50 students to whom you want to send information you should call the makeBooking function 50 times. So changing your main in
int main ()
{
for (int i = 0; i < 50; i++) {
makeBooking();
}
return 0;
}
should do the trick.
However, a more elegant solution would be to send the index i as a parameter in your function. So the code would be:
patientinfo emp[50];
void makeBooking(int i)
{
ofstream outputFile;
outputFile.open("smt.bin", std::ofstream::in | std::ofstream::out | std::ofstream::app);
// int i=num; you don't need these anymore
// num+=1;
cout<< endl << endl << endl << endl << endl << endl
<< setw(30)<<"First Name : ";
cin>>emp[i].PatientFname;
outputFile <<emp[i].PatientFname <<",";
cout<< setw(30)<<"Last Name : ";
cin>>emp[i].PatientLname;
outputFile <<emp[i].PatientLname <<",";
cout<< setw(30)<<"Age : ";
cin>>emp[i].Age;
outputFile <<emp[i].Age <<",";
}
int main ()
{
char response;
for (int i = 0; i < 50;) {
cout << "Do you want to add another person?";
cin >> response;
if (response == 'y')
makeBooking(i++);
else if (respinse == 'n')
break;
else
cout << "Undefined response";
}
return 0;
}
I want to find a string in a file and replace it with user input.
Here is my rough code.
#include <iostream>
#include <fstream.h>
#include <string.h>
int main(){
istream readFile("test.txt");
string readout,
search,
replace;
while(getline(readFile,readout)){
if(readout == search){
// How do I replace `readout` with `replace`?
}
}
}
UPDATE
Here is the code that solved my problem
test.txt:
id_1
arfan
haider
id_2
saleem
haider
id_3
someone
otherone
C++ Code:
#include <iostream>
#include <fstream>
#include <string>
using namesapce std;
int main(){
istream readFile("test.txt");
string readout,
search,
firstname,
lastname;
cout << "Enter the id which you want to modify";
cin >> search;
while(getline(readFile,readout)){
if(readout == search){
/*
id remains the same
But the First name and Last name are replaced with
the user `firstname` and `lastname` input
*/
cout << "Enter new First name";
cin >> firstname;
cout << "Enter Last name";
cin >> lastname;
}
}
}
Suppose:
A user searches for id id_2. After that user enter First name and Last name Shafiq and Ahmed.
After runing this code the test.txt File must modify the record like that:
…
id_2
Shafiq
Ahmad
…
Only the id_2 record changes, the remaining file will stay the same.
This should work. I used string::find to find the desired substring within each line, and string::replace to replace it if something has been found.
Edit: I forgot about the case where the word occurs multiple times per line. Added a while to fix this.
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
ifstream in(argv[1]);
ofstream out(argv[2]);
string wordToReplace(argv[3]);
string wordToReplaceWith(argv[4]);
if (!in)
{
cerr << "Could not open " << argv[1] << "\n";
return 1;
}
if (!out)
{
cerr << "Could not open " << argv[2] << "\n";
return 1;
}
string line;
size_t len = wordToReplace.length();
while (getline(in, line))
{
while (true)
{
size_t pos = line.find(wordToReplace);
if (pos != string::npos)
line.replace(pos, len, wordToReplaceWith);
else
break;
}
out << line << '\n';
}
}
I would do what #stefaanv said:
#include <iostream>
#include <fstream.h>
#include <string.h>
int main(){
ostream outFile("replaced.txt");
istream readFile("test.txt");
string readout;
string search;
string replace;
while(getline(readFile,readout)){
if(readout == search){
outFile << replace;
}
else {
outFile << readout;
}
}
}
Edit: the above solution works if the information on each line is independent of the information on the other lines. In your update, the information on the name lines is dependent on the information on the id lines. So, to extend the above technique, you'll need to maintain state in the while loop that indicates when you've reached the end of one data block.
#include <iostream>
#include <fstream.h>
#include <string.h>
int main(){
ostream outFile("replaced.txt");
istream readFile("test.txt");
string readout;
string search, Fname, Lname;
unsigned int skipLines = 0;
cout << "Enter id which you want Modify";
cin >> search;
cout << "Enter new First name";
cin >> Fname;
cout << "Enter Last name";
cin >> Lname;
while(getline(readFile,readout)) {
if (skipLines != 0) {
skipLines--;
continue;
}
else if (readout == search) {
outFile << search << endl;
outFile << Fname << endl;
outFile << Lname << endl;
skipLines = 2;
}
else {
outFile << readout;
}
}
}
A slightly more elegant approach would be to store each data block in a struct, which allows you to use overloaded operators << & >>. This makes the code for file reading & writing more clear - it's practically the same as the code for the "data on each line is independent" situation.
#include <iostream>
#include <fstream.h>
#include <string.h>
struct NameRecord {
string id;
string fname;
string lname;
friend std::ostream& operator<<(std::ostream &os, const NameRecord &src);
friend std::istream& operator>>(std::istream &is, NameRecord &dst);
};
std::ostream& operator <<(std::ostream &os, const NameRecord &src) {
os << src.id << endl << src.fname << endl << src.lname << endl;
return os;
}
std::istream& operator >>(std::istream &is, NameRecord &dst) {
// may need to have more code to ignore whitespace, I'm not sure
if (is.good ()) {
is >> dst.id;
}
if (is.good ()) {
is >> dst.fname;
}
if (is.good ()) {
is >> dst.lname;
}
return is;
}
int main(){
ostream outFile("replaced.txt");
istream readFile("test.txt");
NameRecord inRecord, replaceRecord;
cout << "Enter id which you want Modify";
cin >> replaceRecord.id;
cout << "Enter new First name";
cin >> replaceRecord.Fname;
cout << "Enter Last name";
cin >> replaceRecord.Lname;
while (readFile.good()) {
// the >> operator reads the whole record (id, fname, lname)
readFile >> inRecord;
// the << operator writes the whole record
if (inRecord.id == replaceRecord.id) {
outFile << replaceRecord;
}
else {
outFile << inRecord;
}
}
}
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char **argv) {
if (argc < 4) {
cout << "Invalid input" << endl;
cout << "\tchange <old_word> <new_word> <file_list>";
}
fstream fs;
string tmp;
string oldw = argv[1];
string neww = argv[2];
for (int i = 3; i < argc; i++) {
fs.open(argv[i] , ios::in);
while (!fs.eof()) {
getline(fs, tmp);
while (tmp.find(oldw) != string::npos)
tmp.replace(tmp.find(oldw), sizeof(oldw), neww);
cout << tmp << endl;
}
}
fs.close();
return 0;
}
Usage:
./a.out old_word new_word filename
You probably meant to write:
tmp.replace(tmp.find(oldw), oldw.length(), neww);
for this to work properly. sizeof() will most likely always return 4.