Adding values in filestream - c++

For example i have a notepad for numbers.
1 2 3 4 5
Then i want to add 4 in the third line which is 3 so that its new value will be
1 2 7 4 5
Question is how can i do that?
Please help me thank you!
string add;
cout<<"Enter value to be added: ";
cin>>add;
fstream file;
file.open("quantity.txt");

You have not been accurate enough with your question, but I think this is something like what you expect:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main(int argc, const char *argv[]) {
std::string filename;
std::cout << "Enter name of file to modify: ";
std::cin >> filename;
std::ifstream inputFile;
inputFile.open(filename);
if(inputFile.fail()) {
std::cout << "Unable to open file \"" << filename << "\" for reading\n";
return 1;
}
unsigned offset;
std::cout << "Enter offset to modify: ";
std::cin >> offset;
int toAdd;
std::cout << "Enter value to be added to line #" << lineNumber << ": ";
std::cin >> toAdd;
std::vector<int> nums;
for(;;) {
int num;
inputFile >> num;
if(inputFile.eof())
break;
nums.push_back(num);
}
inputFile.close();
if(offset >= nums.length()) {
std::cout << "Offset " << offset << " out of bounds!\n";
return 1;
}
nums[offset] += toAdd;
std::ofstream outputFile;
outputFile.open(filename);
if(outputFile.fail()) {
std::cout << "Unable to open file \"" << filename << "\" for writing\n";
return 1;
}
for(int num : nums) // Warning: C++11
outputFile << num << ' ';
outputFile.close();
}

Related

ifstream usage and user input not outputting content to read

I'm practicing ifstream usage. I want the user to enter the file they want to read, in this example num1.txt specifically. I want the console to read one letter from num1.txt and output it on its own line.
I've ran the code below, and after entering "num1.txt" into the console, I get nothing back. I've tried moving around cout << num << endl; to the inner do statement, but it ends up repeating the number 10 an infinite amount.
What am I doing wrong here?
Contents in num1.txt:
2 4 6 8 10
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string fileName, cont;
ifstream inputFile;
do {
int num = 0;
int total = 0;
cout << "Please enter the file name: ";
cin >> fileName;
inputFile.open(fileName);
if (inputFile.is_open()) {
do {
inputFile >> num;
total += num;
}
while(num > 0);
if (total != 0) {
cout << num << endl;
cout << "Total is: " << total << endl;
}
}
else {
cout << "Failed to open file." << endl;
}
inputFile.close();
cout << "Do you want to continue processing files? (yes or no): " << endl;
cin >> cont;
}
while (cont == "yes");
}
Your inner do loop is not correctly validating that operator>> is actually successful before using num. It should be looking at the stream's error state after each read. The easiest way to do that is to change your do loop into a while loop that uses the result of the read as its loop condition, eg:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string fileName, cont;
ifstream inputFile;
do {
cout << "Please enter the file name: ";
cin >> fileName;
inputFile.open(fileName);
if (inputFile.is_open()) {
int num = 0;
int total = 0;
while (inputFile >> num) {
total += num;
}
inputFile.close();
cout << "Total is: " << total << endl;
}
else {
cout << "Failed to open file." << endl;
}
cout << "Do you want to continue processing files? (yes or no): " << endl;
}
while ((cin >> cont) && (cont == "yes"));
return 0;
}

c++ readfile with varying element amounts per line?

if I have a file like this, say called file.txt
20
25 97
97 5
How would i properly read it given that the second column has missing the second element in the first row?I attempted this
int main()
{
ifstream readFile;
string filename;
cout << "Please enter file name and extention: " << endl;
cin >> filename;
readFile.open(filename);
int row = 0;
int column = 0;
while (readFile >> row >> column)
{
//does something
}
However I get segmenation fault
I would like using std::getline to read lines and std::stringstream to parse the lines.
#include <iostream>
#include <fstream>
#include <sstream>
int main(void) {
std::string filename;
std::string line;
std::ifstream readFile;
std::cout << "Please enter file name and extention: " << std::endl;
std::cin >> filename;
readFile.open(filename);
if (!readFile) {
std::cout << "open error\n";
return 1;
}
while (std::getline(readFile, line)) {
std::stringstream ss(line);
int row = 0, column = 0;
if (ss >> row >> column) {
std::cout << "row = " << row << ", column = " << column << '\n';
} else {
std::cout << "invalid line\n";
}
}
readFile.close();
return 0;
}
Another version (also print partial line):
#include <iostream>
#include <fstream>
#include <sstream>
int main(void) {
std::string filename;
std::string line;
std::ifstream readFile;
std::cout << "Please enter file name and extention: " << std::endl;
std::cin >> filename;
readFile.open(filename);
if (!readFile) {
std::cout << "open error\n";
return 1;
}
while (std::getline(readFile, line)) {
std::stringstream ss(line);
int row = 0, column = 0;
bool row_valid = false, column_valid = false;
if (ss >> row) row_valid = true;
if (ss >> column) column_valid = true;
std::cout << "row = ";
if (row_valid) std::cout << row; else std::cout << "(none)";
std::cout << ", column = ";
if (column_valid) std::cout << column; else std::cout << "(none)";
std::cout << '\n';
}
readFile.close();
return 0;
}
Yet another version (support lines with 3 integers and more):
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
int main(void) {
std::string filename;
std::string line;
std::ifstream readFile;
std::cout << "Please enter file name and extention: " << std::endl;
std::cin >> filename;
readFile.open(filename);
if (!readFile) {
std::cout << "open error\n";
return 1;
}
while (std::getline(readFile, line)) {
std::stringstream ss(line);
std::vector<int> lineInts;
int data;
while (ss >> data) lineInts.push_back(data);
std::cout << lineInts.size() << " elements:";
for (int d : lineInts) std::cout << ' ' << d;
std::cout << '\n';
}
readFile.close();
return 0;
}

c++ ifstream not reading integers

My ifstream is not reading integers correctly. My main is as follows:
#include <fstream>
#include <vector>
#include <string>
int main() {
vector<int> myvec;
Tree myAVL;
ifstream myfile;
string filename;
cout << "Enter the file name you would like to use: ";
cin >> filename;
myfile.open(filename);
while (!myfile) {
cout << "ERROR: INVALID FILENAME -- Please input valid filename: ";
cin >> filename;
myfile.open(filename);
}
while (!myfile.eof()) {
int x;
myfile >> x;
if (myvec.size() == 0) {
myvec.push_back(x);
myAVL.insert(x);
continue;
}
if (checkVecDuplicate(myvec, x))
{
myAVL.insert(x);
myvec.push_back(x);
}
}
for (int i = 0; i < myvec.size(); i++)
{
cout << myvec[i];
}
cout << endl << endl;
Node* temp = myAVL.head;
myAVL.inorder(temp);
cout << endl << endl;
myAVL.preorder(temp);
cout << endl << endl;
system("pause");
return 0;
}
My text file I'm trying to read in is:
14
32
64
55
1
12
3
4
16
72
125
54
Why is this not reading any of the integers? At myfile >> x it's reading in a null value for the integer and I have no clue why. Thank you!

Reading from a file and displaying it backwards

I'm trying to write a program to read from a file and display the text backwards. - My loop backward loop is not working. Any suggestions?
- Also if I'm reading a file that only contain floats integers or floats, how would I display them all as float?
Thanks,
#include <iostream>
#include <fstream>
using namespace std;
void seeReverseText(char fileName[])
{
ifstream fin(fileName);
if (fin.fail())
{
cout << "Error opening file " << fileName << endl;
return;
}
cout.setf(ios::showpoint);
cout.precision(2);
cout.setf(ios::fixed);
int i = 0;
cout << "New order:\n";
while (!fin.eof())
{
// this is what I was trying to do
// i++;
// for (i--; i >= 0; i--)
// fin >> fileName[i];
// cout << "' " << fileName[i] << "'";
fin >> fileName;
cout << fileName << endl;
}
fin.close();
}
int main()
{
char fileName[256];
cout << "Enter the filename: ";
cin >> fileName;
seeReverseText(fileName);
return 0;
}
Try something more like this instead:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
void seeReverseText(const std::string &fileName)
{
std::ifstream fin(fileName);
if (!fin)
{
std::cout << "Error opening file " << fileName << std::endl;
return;
}
std::cout.setf(std::ios::showpoint);
std::cout.precision(2);
std::cout.setf(std::ios::fixed);
std::cout << "New order:\n";
std::string line;
while (std::getline(fin, line))
{
std::reverse(line.begin(), line.end());
std::cout << line << std::endl;
}
}
int main()
{
std::string fileName;
std::cout << "Enter the filename: ";
if (std::cin >> fileName)
seeReverseText(fileName);
return 0;
}

Read File Line by line and output the first coloumn

I am new to c++ and am trying to do a string search for 2 words(double and triple) in a file and print the line on which they are found. Some lines only have the word "double" and some only have the word "triple".
The code doesn't seem to output the words, it just prints the last line at the end of the loop.
I forgot to add that I need to print the first element of the line on which the word is found, I am able to locate the line where the word is found, however, it doesnt seem to print the first element on the file.
Here is my code.
int main(int argv, char *argc[]){
const string filen("test.txt");
ifstream inFile(filen.c_str());
string line = "";
char IDList[10];
string ID = "";
char* double_word = "double"; // test variable to search in file
char* triple_word = "triple";
stringstream ss;
string word = "";
unsigned int currentLine = 0;
// iterate through each line and check if the words double or triple exist.
while(getline(inFile, line)){
currentLine++;
if (line.find(double_word) != string::npos) {
cout << "found the word \"double\" on line: " << currentLine << endl;
// this part takes the input file and reads the first character of the line i.e. the ID and adds it to the IDList
// string array.
while(inFile >> IDList){
cout << "File Id: " << IDList << endl;
inFile.ignore(numeric_limits<streamsize>::max(), ' ');
for(int i=0;i<10;i++){
ss << IDList[i] << endl;
}
word = ss.str();
}
}
else if(line.find(triple_word) != string::npos){
cout << "found the word \"triple\" on line: " << currentLine << endl;
// now take the id of this file and add it to a different queue.
while(inFile >> IDList){
cout << "File Id: " << IDList << endl;
inFile.ignore(numeric_limits<streamsize>::max(), ' ');
for(int i=0;i<10;i++){
ss << IDList[i] << endl;
}
word = ss.str();
}
}
else if(line.find(double_word) && line.find(triple_word) != string::npos){
cout << "Found both words double and triple in line: " << currentLine << endl;
while(inFile >> IDList){
cout << "File Id: " << IDList << endl;
inFile.ignore(numeric_limits<streamsize>::max(), ' ');
for(int i=0;i<10;i++){
ss << IDList[i] << endl;
}
word = ss.str();
}
}
else{
cout << "neither word found, moving to next line" << endl;
}
}
inFile.close();
cout << "Id's added to the queue" << word << endl;
return 0;
}
I think you can simplify your code and write something like this:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using std::string;
using std::vector;
using std::cout;
using std::cin;
int main(int argc, char* argv[]) {
const string filen("test.txt");
std::ifstream inFile(filen.c_str());
string line;
string double_word = "double"; // test variable to search in file
string triple_word = "triple";
vector<string> IDs;
unsigned int currentLine = 0;
// iterate through each line and check if the words double or triple exist.
while(getline(inFile, line)){
currentLine++;
bool found_d_word = line.find(double_word) != string::npos;
bool found_t_word = line.find(triple_word) != string::npos;
if ( found_d_word && !found_t_word )
cout << "found the word \"double\" on line: " << currentLine << '\n';
if ( found_t_word && !found_d_word )
cout << "found the word \"triple\" on line: " << currentLine << '\n';
if ( found_d_word && found_t_word )
cout << "Found both words double and triple in line: " << currentLine << '\n';
if ( found_d_word || found_t_word ) {
std::istringstream ss{line};
string ID;
ss >> ID;
cout << "File Id: " << ID << '\n';
// my guess: store all the IDs in one vector
IDs.push_back(ID);
} else {
cout << "neither word found, moving to next line\n";
}
}
inFile.close();
return 0;
}
One of the problems with your code is that you first read a line of the input file (with getline), put that in a string and then, when the word "double" or "triple" is found in the string, you try to read the ID from the file while you should read it from the same string.
Try this,
#include "iostream"
#include "string"
#include "sstream"
#include "fstream"
using namespace std;
int main()
{
stringstream y; string x; int lc=0, id;
ifstream fin("file.txt");
while (getline(fin, x))
{
++lc;
y.str(x);
y >> id;
bool d=x.find("double")!=string::npos;
bool t=x.find("triple")!=string::npos;
if (d and t)
cout << "found words double and triple on line " << lc
<< ", id is " << id << endl;
else if (d)
cout << "found word double on line " << lc
<< ", id is " << id << endl;
else if (t)
cout << "found word triple on line " << lc
<< ", id is " << id << endl;
}
}