I am currently trying to read a bunch of words from a .txt document and can only manage to read the characters and display them yet. I'd like to do the same but with whole words.
My code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream infile("banned.txt");
if (!infile)
{
cout << "ERROR: ";
cout << "Can't open input file\n";
}
infile >> noskipws;
while (!infile.eof())
{
char ch;
infile >> ch;
// Useful to check that the read isn't the end of file
// - this stops an extra character being output at the end of the loop
if (!infile.eof())
{
cout << ch << endl;
}
}
system("pause");
}
Change char ch; to std::string word; and infile >> ch; to infile >> word; and you're done. Or even better do the loop like this:
std::string word;
while (infile >> word)
{
cout << word << endl;
}
Related
I'm currently writing a program that reads in a .txt file. The program is supposed to read a character, output an error, and continue reading the rest of the lines, and follow suit. I'm not sure where I'm going wrong.
#include <iostream>
#include <cmath>
#include <string>
#include <stream>
using namespace std;
int main(){
double runningTotal;
int c = 0;
string fileName;
ifstream infile;
cout << "Enter a file name\n";
cin >> fileName;
infile.open(fileName.c_str());
if (!infile.is_open()) {
cout<<"Error! invalid entry please retry!\n";
}
else {
string line;
int a, b;
while (!inflile.fail()) {
infile >> a >> b;
c = a + b;
runningTotal = c;
cout <<a<<" + "<<b<<" = " << runningTotal<<endl;
}
getline(infile, line, '\n');
if (infile.fail()){
getline(infile, line, '\n');
cout<<"stop being stupid\n";
}
}
}
I need to delete all the occurencies of a string in a file.
I receive the text as a string and erase every occurencies.
After I deleted all the occurencies i don't know how to save the string back to the file.
I've tried to close the file and wit ofstream to write in it but it didn't work.
#include <iostream>
#include <fstream>
#include <string>
int main () {
std::string file_contents = "";
std::ifstream myfile ("text.txt");
char ch;
if (myfile.is_open())
{
// READ FILE CONTENTS AS STRING
while ( myfile >> std::noskipws >> ch)
{
file_contents += ch;
}
// DISPLAY STRING
std::cout << file_contents << '\n';
// GET WORD TO BE DELETED
std::string word;
std::cout << "Please enter word to be deleted: ";
std::cin >> word;
std::string::size_type found;
std::string new_text;
//DELETE WORD FROM STRING
bool ok=0;
do{
found = file_contents.find(word);
ok=1;
if (found!=std::string::npos)
{
std::cout << word << " found at: " << found << '\n';
file_contents.erase(found, word.length());
std::cout << file_contents << '\n';
}
else
ok==0;
new_text=file_contents;
}while(ok==1);
myfile.close();
}
else std::cout << "Unable to open file";
return 0;
}
Okay so you must close ifstream instance before proceeding to write to the file again.
After closing the file, modify the content and then open the same file for write using ofstream and simply write the content.
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string file_contents = "";
std::ifstream myfile("text.txt");
char ch;
if (myfile.is_open())
{
// READ FILE CONTENTS AS STRING
while (myfile >> std::noskipws >> ch)
{
file_contents += ch;
}
myfile.close();
}
else {
std::cout << "Unable to open file";
return -1; // no need to continue if can't read it
}
// DISPLAY STRING
std::cout << file_contents << '\n';
// GET WORD TO BE DELETED
std::string word;
std::cout << "Please enter word to be deleted: ";
std::cin >> word;
//DELETE WORD FROM STRING
size_t found;
while ((found = file_contents.find(word)) != file_contents.npos)
{
std::cout << word << " found at: " << found << '\n';
file_contents.erase(found, word.length());
std::cout << file_contents << '\n';
}
// this will open in text mode and will replace all existing content
std::ofstream out("text.txt");
if (out.is_open()) {
out << file_contents;
out.close();
}
else {
std::cout << "Unable to open file for writing.\n";
return -2; // for failure to open for write
}
return 0;
}
Note: the loop you had went infinitely when I tried to execute it, I had to change it to the code shown above. Also, new_text is completely unnecessary, why have it?
The simpliest way is first to open as input stream. When finish open as output stream to write. It is not the only way you can do that.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
std::string file_contents = "";
{
std::ifstream myfile ("text.txt");
if (! myfile.is_open())
{
else std::cout << "Unable to open file";
return 1;
}
// READ FILE CONTENTS AS STRING
char ch;
while ( myfile >> std::noskipws >> ch) file_contents += ch;
myfile.close();
}
{
std::string word;
std::cin >> word; // GET WORD TO BE DELETED
std::string::size_type found;
while((found = file_contents.find(word))!=std::string::npos)
file_contents.erase(found, word.length());
std::ofstream myfile ("text.txt");
myfile << file_contents<< std::flush;
myfile.close();
}
return 0;
}
This is my text file:
12345 shoe 5 0
34534 foot 72 1
34562 race 10 0
34672 chicken 24 150
88 pop 65 0
I need to take this file and go row by row, assign the first number as an identifier itemNum, second word as itemName, third number as itemPrice, and last number as itemAdjusmentValue. I will need to perform arithmetic with the last two numbers itemPrice and itemAdjusmentValue.
Code so far:
using namespace std;
// making a struct to store each value of the cuadre
struct Cuadre
{
int itemNum;
string itemName;
int itemPrice;
int itemAdjusment;
};
int main (){
ifstream infile("sheet_1.txt");
string checkLine;
if (infile.is_open()){
while ( infile.good()){
getline (infile, checkLine);
cout << checkLine << endl;
}
}
else
cout << "error with name of file" << endl;
vector<Cuadre> procedures;
Cuadre line;
while(Cuadre >> line.itemNum >> line.itemName >> line.itemPrice >> line.itemAdjusment){
procedures.push_back(line);
}
This code generates an error on the last while statement
expected primary-expression before '>>' token
I cant really find a specific tutorial on how to do this, and i've looked a good amount.
From the code you posted, (with reference to the >> istream operators) it looks like you want to stream the contents of the string data read from your file into the members of a struct.
It is not possible to stream directly from a std::string (eg: checkLine >> x >> y >> z), as string does not provide a streaming interface.
In order to do that you need to use a stream, such as std::stringstream.
You could populate a with your string checkLine, and then stream from that into your data members
std::stringstream ss(checkLine);
ss >> line.itemNum >> line.itemName >> line.itemPrice >> line.itemAdjusment;
Example code:
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
// making a struct to store each value of the cuadre
struct Cuadre
{
int itemNum;
string itemName;
int itemPrice;
int itemAdjusment;
};
int main (){
ifstream infile("sheet_1.txt");
string checkLine;
vector<Cuadre> procedures;
if (infile.is_open()){
while ( infile.good()){
getline (infile, checkLine);
cout << checkLine << endl;
Cuadre line;
std::stringstream ss(checkLine);
ss >> line.itemNum >> line.itemName >> line.itemPrice >> line.itemAdjusment;
procedures.push_back(line);
}
}
else
cout << "error with name of file" << endl;
return 0;
}
You need to push into the vector inside the loop that reads from the file. And you should be getting the fields from checkLine -- Cuadre is a type name, not a variable you can read from. But to do that you need to create a stringstream.
int main (){
ifstream infile("sheet_1.txt");
string checkLine;
vector<Cuadre> procedures;
if (infile.is_open()){
while (getline (infile, checkLine)){
Cuadre line;
cout << checkLine << endl;
stringstream linestream(checkline);
if (linestream >> line.itemNum >> line.itemName >> line.itemPrice >> line.itemAdjusment) {
procedures.push_back(line);
} else {
cout << "incorrect line" << endl;
break;
}
}
}
else {
cout << "error with name of file" << endl;
}
}
while (infile.good()) is also not correct, it's essentially the same as while (!infile.eof()). See Why is iostream::eof inside a loop condition considered wrong?
You can try reading directly into struct as well:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
struct Cuadre
{
int itemNum;
std::string itemName;
int itemPrice;
int itemAdjusment;
};
int main()
{
std::vector<Cuadre> procedures;
std::ifstream infile("sheet_1.txt");
while (infile)
{
Cuadre line;
if (infile >> line.itemNum >> line.itemName >> line.itemPrice >> line.itemAdjusment)
procedures.push_back(line);
else
break;
}
if (!procedures.empty())
{
for (auto &p : procedures)
std::cout
<< "itemNum: " << p.itemNum << "\t"
<< "itemName: " << p.itemName << "\t"
<< "itemPrice: " << p.itemPrice << "\t"
<< "itemAdjusment: " << p.itemAdjusment
<< std::endl;
}
else
std::cout << "error with file or data" << std::endl;
return 0;
}
Prints:
itemNum: 12345 itemName: shoe itemPrice: 5 itemAdjusment: 0
itemNum: 34534 itemName: foot itemPrice: 72 itemAdjusment: 1
itemNum: 34562 itemName: race itemPrice: 10 itemAdjusment: 0
itemNum: 34672 itemName: chicken itemPrice: 24 itemAdjusment: 150
itemNum: 88 itemName: pop itemPrice: 65 itemAdjusment: 0
If you define an overload of >> for your type Cuadre, you can read directly from the file into Cuadre objects.
std::istream& operator>>(std::istream& is, Cuadre & cuadre)
{
std::string s;
getline(is, s);
std::cout << s;
std::stringstream ss(s);
ss >> cuadre.itemNum >> cuadre.itemName >> cuadre.itemPrice >> cuadre.itemAdjusment;
return is;
// or without logging
return is >> cuadre.itemNum >> cuadre.itemName >> cuadre.itemPrice >> cuadre.itemAdjusment;
}
int main (){
ifstream infile("sheet_1.txt");
vector<Cuadre> procedures;
for (Cuadre line; infile >> line;) {
procedures.push_back(line);
}
// or with #include <algorithm>
std::copy(std::istream_iterator<Cuadre>{ infile }, {}, std::back_inserter(procedures));
}
I am trying to read a text-file based using the >> stream operator, but this seems to read the file word by word:
void printFile(char filename[])
{
ifstream input;
input.open(filename);
char output[50];
if (input.is_open()) {
while (!input.eof()) {
input >> output;
cout << output << endl;
}
}
else cout << "File is not open!";
input.close();
cout << endl;
}
The only problem with this is that it won't print out the linebreaks.
Please note that I'm still learning C++ and the goal is to achieve this without using strings (so without getline). Is there any way of doing this, or is it simply impossible?
Thanks to #odin I found the solution by reading the file by character instead of by word:
void printFile(char filename[])
{
char ch;
fstream fin(filename, fstream::in);
while (fin >> noskipws >> ch) {
cout << ch;
}
fin.close();
}
You can identify an end of a line as follow
int main(){
char ch;
fstream fin("filename.txt", fstream::in);
while(fin >> noskipws >> ch){
if(ch == '\n') { // detects the end of the line
cout << "This is end of the line" << endl;
}
}
return 0;
}
Here is the code I have so far.
What I need to do is read from two different text files, Matrix A and Matrix B.
I can do this however for each text file matrix I read it only comes up with
1 0 0
(so basically the first line) where the whole text file for Matrix A is in fact
1 0 0
2 0 0
3 0 0
so does anybody know how I can do this?
Thanks!
#include <iostream> //declaring variables
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
string code(string& line);
int main()
{
ofstream outf;
ifstream myfile;
string infile;
string line;
string outfile;
cout << "Please enter an input file (A.txt) for Matrix A or (B.txt) for Matrix B" << endl;
cin >> infile; //prompts user for input file
if (infile == "A.txt")
{ //read whats in it and write to screen
myfile.open("A.txt");
cout << endl;
getline (myfile, line);
cout << line << endl;
}
else
if (infile == "B.txt")
{
myfile.open("B.txt");
cout << endl;
getline (myfile, line);
cout << line << endl;
}
else
{
cout << "Unable to open file." << endl;
}
//{
//while("Choose next operation");
//}
return 0;
}
Well, getline obviously gets one line.
You should read line by line until the end of file, and you can achieve that with, for example:
while (getline(myfile, line))
out << line << endl;
This means: while there is a line to get from myfile, write that line to the output stream.
You are reading only once, so this is not a miracle. You will need to use a while or for loop for continous reading. You would be writing something like this:
while (getline (myfile, line))
cout << line << endl;
This would be the whole code to write:
#include <iostream> //declaring variables
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
string code(string& line);
int main()
{
ofstream outf;
ifstream myfile;
string infile;
string line;
string outfile;
cout << "Please enter an input file (A.txt) for Matrix A or (B.txt) for Matrix B" << endl;
cin >> infile; //prompts user for input file
if (infile == "A.txt")
{ //read whats in it and write to screen
myfile.open("A.txt");
cout << endl;
while (getline (myfile, line))
cout << line << endl;
}
else
if (infile == "B.txt")
{
myfile.open("B.txt");
cout << endl;
while (getline (myfile, line))
cout << line << endl;
}
else
{
cout << "Unable to open file." << endl;
}
//{
//while("Choose next operation");
//}
return 0;
}
Using getline is the easiest way:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
void read_file_line_by_line(){
ifstream file;
string line;
file.open("path_to_file");
while (getline (file, line))
cout << line << endl;
}
int main(){
read_file_line_by_line();
return 0;
}