Delimit Sentences in C++, after each period - c++

Sorry if I am brief I had a lot of trouble putting this code up here.
I want to basically parse the file "question.txt"
and every time I see a period i want a new line
basically:
hey jim.(new line)
hey tim.(newline)
int main(){
ifstream openQuiz;
openQuiz.open("questions.txt");
string line;
//int count = 0;
//Check for errors
if (openQuiz.fail()) {
cerr << "Error opening file" << endl;
}
//Reading from beginning to ending;
while (!openQuiz.eof()) {
}
openQuiz.close();
return 0;
}

You could use an fstream instead of an ifstream. The difference is that fstreams can do input and output at the same time.
Then you could simply read the characters one by one. Whenever you read a '.' write a newline.

#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream f("file.txt");
char c;
while (f.get(c)) {
cout << c;
if (c=='.') cout << endl;
}
return 0;
}
How's this for you?
You can read more about std::istream::get() here http://www.cplusplus.com/reference/istream/istream/get/

Related

Having an issue passing an array to a Function as only first word is printed c++

I am new to passing values to functions, please guide me what I am doing wrong here, thanks!
The question: Write a C++ program in which, read a c-string sentence
one by one from a file “sentence .txt”. Now your task is to break each
word of sentence into another c-string word, now write that word into
a file “word.txt”. Note : You must create atleast 1 function to
separate the words from sentence, you cannot use strings.
#include <iostream>
#include <fstream>
using namespace std;
char sentence2word(char array[100])
{
ofstream fout2;
fout2.open("word.txt");
fout2 << array << endl;
return array[100];
}
int main()
{
ifstream fin;
fin.open("sentence.txt");
char array[100];
fin >> array;
cout << "Output successful!";
sentence2word(array);
return 0;
system("pause");
}
The following program show how to get started with reading and writing from/into text files in C++. This is just to get you started and in practice i use std::string and std::istringstream to do this but in your note it is written that we cannot use strings so i did not use std::string. The program reads line by line from an input.txt file and write word by word into an output.txt file.
#include <iostream>
#include <fstream>//needed to read/write files
#define MAX_NUMBER_OF_CHARACTERS 500
using namespace std;
//function that writes lines word by word into output.txt
void writeWordByWord(std::ofstream &m_outFile, char (&lineArg)[MAX_NUMBER_OF_CHARACTERS])
{ int i = 0;
while(lineArg[i] != '\0')
{
if(lineArg[i] != ' ')
{m_outFile << lineArg[i];
//std::cout<< lineArg[i]<<" wrote"<<std::endl;
++i;
}
else{
m_outFile << '\n';
++i;
}
}
//m_outFile << '\n';
}
int main()
{
cout << "Hello World" << endl;
char line[MAX_NUMBER_OF_CHARACTERS];
std::ifstream inFile("input.txt");
std::ofstream outFile("output.txt");
while(inFile.getline(line, MAX_NUMBER_OF_CHARACTERS, '\n'))
{
std::cout<<line<<std::endl;
writeWordByWord(outFile, line);
}
inFile.close();
outFile.close();
return 0;
}

c++ how to read and write from a specific line in a textfile?

hi I am trying to read a specific line from a text file update that and put it back to the same line without affecting the other lines in c++
here I am trying to execute the code and values get added when I re-execute it
#include <iostream>
#include <stream>
#include <stdio.h>
#include <string>
#include <stream>
using namespace std;
void stringGen(char num){
ifstream ifile;
ifile.open("example1.txt");
if(ifile) {
int LINE = 5;
string line;
ifstream myfile1 ("example1.txt");
for (int i = 1; i <= LINE; i++)
getline(myfile1, line);
cout << line<<endl;
stringstream geek(line);
int num=0;
geek>>num;
if(num<61004){
num=num+1;
ofstream MyFile("example1.txt");//
MyFile.close();
}
else{
num=61001;
ofstream MyFile("example1.txt");//
MyFile << num;
MyFile.close();
}
}
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("example1.txt");//
MyFile << num+1;
MyFile.close();
}
}
int main (){
char num;
stringGen(num);
return 0;
}
At first, you need to understand, how files, with lines are stored. Simplified, it is a sequence of bytes, one byte after the other. There maybe some special characters in this byte sequence, which people can interprete as the end of a line, e.g. '\n'. But also other characters or even more than one character is possible:
If you look at the following text.
Hello1
World1
Hello2
World2
it maybe stored in a file like this:
Hello1\nWorld1\nHello2\nWorld2\n
And just because we interprete a '\n' as the end of the line, we can "see" lines in there.
So, if you want to modify a line, then you would need to find the start position of the thing that we interprete as a line in the file, and then modify some bytes.
That can of course only be done, if the length of the "line" will not change. Then you could use "seek" functions and overwrite the needed bytes.
In reality, nobody would do that. Normally, you would read "lines" of the file into some kind of memory buffer, then do the modification there and then write back all lines.
For example, you would define a std::vector and then read all lines, by using std::getline and push_back the lines in the std::vector.
The modifications will be done in the std::vector, and the all data will be written back to the file, overwriting all "old" data.
There are more answers to this question. If you have any more specific question, I will answer again
Some simple example code
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main() {
// Here we will store all lines of the text file
std::vector<std::string> lines{};
// Open the text file for reading and check, if it could be opened
if (std::ifstream textfileStream{ "test.txt" }; textfileStream) {
// Read all lines into our vector
std::string oneLine{};
while (std::getline(textfileStream, oneLine)) {
// Add the just read line to our vector
lines.push_back(oneLine);
}
// For test purposes, modify the first line
if (not lines.empty()) lines[0] = "MODIFIED";
}
else std::cerr << "\nError: Could not open input text file\n";
// Write back data
// Open the text file for writing and check, if it could be opened
if (std::ofstream textfileStream{ "r:\\test.txt" }; textfileStream) {
// Iterate over all lines and wriite to file
for (const std::string& oneLine : lines)
textfileStream << oneLine << '\n';
}
else std::cerr << "\nError: Could not open output text file\n";
return 0;
}
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
void stringGen(char num){
int count=0;
int a;
string line,check,linex;
string msg="Message_Handler:";
fstream ifile;
ifile.open("sample.txt",ios::in|ios::out);
if(ifile){
while(getline (ifile,line)) {
if (line.find("Message_Handler:") == 0){
check=line.substr(16,5);
count++;
a=ifile.tellp();
}
}
ifile.close();
if(count==0){
int num=61001;
cout<<num<<endl;
num=num+1;
ofstream examplefile ("sample.txt",ios::app);
examplefile<<"Message_Handler:"<<num;
examplefile.close();
}
if(count==1){
cout<<check<<endl;
stringstream geek(check);
int num=0;
geek>>num;
if(num<61004){
num=num+1;
stringstream ss;
ss << num;
string nums = ss.str();
fstream MyFile("sample.txt",ios::in|ios::out);
MyFile.seekp(a-5);
MyFile<<nums;
}
else{
int num=61001;
stringstream ss;
ss << num;
string nums = ss.str();
fstream MyFile("sample.txt",ios::in|ios::out);
MyFile.seekp(a-5);
MyFile<<nums;
}
}
}
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("sample.txt",ios::app);
MyFile <<"Message_Handler:"<< num+1;
MyFile.close();
}
}
int main (){
char num;
stringGen(num);
return 0;
}

how to create a string from a txt file

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;
}

looping over numbers from a txt file using fstream

I'm a bit new to C++ so I'm trying to keep things simple.
I'm trying to apply a loop that simply prints out each number from a txt file. And there are A LOT of numbers.
I've been trying to do this with a for loop but with no success. Here's just one of my attempts:
int main() {
fstream myFile;
myFile.open("resources/numbers.txt");
if (myFile) {
cout << "This file is opened\n";
}
else
return EXIT_FAILURE;
for (i = 1; i<n; i++){
myFile >> n;
cout << n;
}
return 0;
}
I'd prefer not to use arrays or getLine. I just want to take every number from the txt file and print it to the user until every number is printed.
Is there an easy way to do this?
Thanks a million!
Here is how I’d print the number in the file:
std::copy(std::istream_iterator<int>(myFile),
std::istream_iterator<int>(),
std::ostream_iterator<int>(std::cout, “\n”));
In you example you didn’t declare n so it isn’t clear what the proper type is. The code assumes int and that <algorithm> and <iterator> are included.
#include <cstdlib> // EXIT_FAILURE
#include <iostream>
#include <fstream>
int main()
{
std::ifstream myFile{ "resources/numbers.txt" }; // use c-tor to open
// ^ ifstream ... we only want to read
if (!myFile.is_open()) {
std::cerr << "File couldn't be opened for reading :(\n\n";
return EXIT_FAILURE;
}
std::cout << "File is open for reading.\n\n";
int number;
while(myFile >> number) // as long as integers can be extracted from the stream,
std::cout << number << '\n'; // print them.
} // no need to return anything as main() returns 0 when not return statement
// is present.

Counting word occurence in textfile

Here's the code that I based here http://www.thecrazyprogrammer.com/2015/02/c-program-count-occurrence-word-text-file.html. (new in c++)
#include <iostream>
#include <fstream>
#include<cstring>
using namespace std;
int main()
{
// std::cout << "Hello World!" << std::endl;
// return 0;
ifstream fin("my_data.txt"); //opening text file
int count=0;
char ch[20],c[20];
cout<<"Enter a word to count:";
gets(c);
while(fin)
{
fin>>ch;
if(strcmp(ch,c)==0)
count++;
}
cout<<"Occurrence="<<count<<"n";
fin.close(); //closing file
return 0;
}
Error in Patter Counting
my_data.txt has only 3 "world" in it, but as I run the program, it results to
here's the textfile's content
What could go wrong?
A solution using std::string
int count = 0;
std::string word_to_find, word_inside_file;
std::ifstream fin("my_data.txt");
std::cout << "Enter a word to count:";
std::cin >> word_to_find;
while (fin >> word_inside_file) {
if (word_to_find == word_inside_file )
count++;
}
std::cout << "Occurrence=" << count << "";
If you want to find all occurrences inside other strings as well, as mentioned in the comments, you can do something like this:
...
while (fin >> word_inside_file) {
count += findAllOccurrences(word_to_find, word_inside_file);
}
...
Inside findAllOccurrences(std::string, std::string) you will implement a "find all string occurrences inside another string" algorithm.
If you are new to c++ you shouldn't really use gets. Read about "buffer overflow vulnerability". gets() is more like c-style. You should consider using std::cin.