How to print output in a file after a few empty lines - c++

What I want to do here, is print the word "hello", first at the beginning, then skip some lines, then print it again in the file. The number of lines I need to skip is specified by the user. The file may or may not be empty, and if it's not empty, I don't want to change data on lines other than I need to print. If the file is empty, then it has to skip empty lines and still print after some lines.
Here is my code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
ifstream f1("temp.txt");
ofstream f2("temp.txt");
int r;
cout << "Enter number of lines to skip:" ;
cin >> r;
f2 << "hello";
string org = "";
while(--r){
getline(f1, org);
cout << "org: "<< endl;
}
int pos = f1.tellg();
cout << "pos: " << pos << endl;
f2.seekp(pos, f2.beg);
f2 << "hello";
}
The output I receive when I input r=3, for example, and the file is empty:
org:
org:
pos: -1
Also, the file remains empty. No output.
tellg() does not seem to work.
Anyone has any idea what to do here?

First of all, don't read and write to the same file. Files are opened in different modes so this won't work. But aside from that it is also better practice to parse your input, then operate on it in memory and write out the desired result. so open the file, read what is of interest (you can store a map with the lines that are interesting, or read the whole thing into memory) then do your operations on it, and write out the result.

Related

What could cause this error to create when using the array? Solution?

a bit new here, been back and forth trying to solve the issue of getline. Which I found the source of the error was due to intext[18]. Once I remove the array all errors go away. Problem is the document I have has 19 lines of data I need to retrieve so rather than typing out each string I decided to attempt to put it all in array. I am very new to c++ and this is the only time so far that I have hit a wall. I do apologize in advance if this has been solved. Ive been searching all day without resolve.
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <array>
using namespace std;
int main()
{
ifstream inFile;
string intext[18];
inFile.open("HW3_Data_W.txt");
while (inFile.is_open()) {
getline(inFile, intext);
cout << "Data from the file:" << endl;
cout << "Item 1: " << intext << endl;
break;
inFile.close();
}
}
You're trying to assign string value to string array variable, you should
getline(inFile, intext[i]);
where i is the number of line.
Also your array can only contain 18 lines of text, because you declared it this way. If you want to read files that have exactly 19 lines you should declare it this way:
string intext[19];
If you want your program to read any number of lines you should use std::vector.
Besides that, your while loop will only repeat once. because you break it unconditionally. I guess what you wanted to do is something like that:
inFile.open("HW3_Data_W.txt");
int i = 1;
while (inFile.is_open()) {
getline(inFile, intext[i]);
i = i + 1;
cout << "Data from the file:" << endl;
cout << "Item 1: " << intext << endl;
if(inFile.eof) continue;
inFile.close();
}
This code should work but is unnecessarily complicated. Your while condition checks if your file is open, but it will be open until you close it and you want to close it when you reach the end of the file. So your while condition look like that:
while (getline(inFile, intext[i]))
getline will return value that is convertible to false if it reaches last line of your file so your while will go until you read while file. And you have to check if file is open before your while, then you should close file after while. So something like that:
inFile.open("HW3_Data_W.txt");
int i = 0;
if(!inFile.is_open())
return EXIT_FAILURE;
while(getline(inFile, intext[i])) {
cout << "Item "<<i<<": " << intext[i] << endl;
}
inFile.close()
Some issues here:
If you have 19 lines to read, then the size of the string array should be at least 19.
Check if the file is opened successfully only once. No need to check in the while condition.
Read into consecutive elements of intext array within while using a counter which is initialized to 0 before the while loop. Increment this counter within the while loop.
Remove break from while as you want to read the whole file.
Do not close ifstream inside the while. Do it after the while loop.

c++ copying console values to a csv

New in C++ and I am trying to copy the values that I read on my console after opening a .csv file to another .csv file that I want to create. Unfortunately it copies only the last value, not the whole. Any help? thanks very much!
int main()
{
ifstream filetocopy("ecommerce.csv");
int d;
while(filetocopy>>d){
cout << d << endl;}
ofstream numbers("testing.csv");
numbers << d << endl;
}
Obvious problems with your approach:
1) You create the output file after you read the entire input file which means you write only the last value to the output file.
2) Even if you fix 1) you would still write the csv values in a wrong order to the output file. Suggestion: read line by line -> print the line on the console -> write the line to the file.
Here's a simple solution to your problem (just an example you can improve it):
#include <iostream>
#include <fstream>
#include <string>
int main () {
std::ifstream filetocopy("ecommerce.csv");
std::ofstream numbers("testing.csv");
std::string line;
while(std::getline(filetocopy, line)) {
std::cout << line << std::endl;
numbers << line << std::endl;
}
return 0;
}
You have two problems here.
First, you didn't create the ofstream to output until after you had already used and discarded most of your data.
Second, in the while loop, all you did was write your data to the standard output and not to file.
To correct the problem, you need to move the ofstream initialization before the while loop and move numbers << d << endl; into the loop.
Think of your ifstream as like an old VCR tape. As you are printing out characters with that while loop
while(filetocopy>>d){
cout << d << endl;}
your ifstream finished "playing". Every loop d gets a new frame of the tape and prints it out. So the tapehead is at the end, and now d is just holding onto the last frame of the credits. So when you write it to your new csv, that's the only value it has left.
Try not printing out all those values first.

.size() string manipulation not reading actual length/size of characters c++

I am trying to read in an essay from a file which I then need to change each beginning letter of a sentence to an upper case letter and then send the corrected essay back to a file called correct.txt. The essay is stored in essay.txt.
So far I am just working with understanding the conversions from files to string in order for me to proceed with the rest of the question. So far, I have a string variable which which holds the essay with the words separated by a single space. I noticed that when I was trying to work with the size of my new string, it was not giving me the correct answer and I cannot figure out why. If you have any suggestions on how I can get it to notice the correct amount of characters, I would really appreciate it.
One more question while you're here, I know that moving forward, in order to change the beginning letters of the sentence to upper case, I need to first find the periods. Once I have this position, I can use pos+2 (including the preceding whitespace after the period) for the character that needs to become upper case. Is this the correct way of going about this and do you have any other tips on how to go forward with this?
Here is my code so far:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
//declaring variables and creating objects
ifstream inputFile;
ofstream outputFile;
char inputFileName[20], outFileName[20];
cout << "Enter name of the file you want to open: " << endl;
cin >> inputFileName;
inputFile.open(inputFileName);
if (inputFile.fail()) {
cout << "Input file opening failed.\n";
exit(1);
}
cout << "Enter name of the file you want to send the output to: " << endl;
cin >> outFileName;
outputFile.open(outFileName);
if (outputFile.fail()) {
cout << "Output file opening failed.\n";
exit(1);
}
//while the file is open, it sends the contents to the string variable "essay"
string essay;
inputFile >> essay;
while (!inputFile.eof()) {
cout << essay << " ";
inputFile >> essay;
}
//this is to check for the correct size of the string "essay" before moving on to the rest of the code
int size = essay.size();
cout << size << endl;
return 0;
}
Your understanding of how the input stream works is incorrect.
The core of your code is this loop:
string essay;
inputFile >> essay;
while (!inputFile.eof()) {
cout << essay << " ";
inputFile >> essay;
}
What this does is that it reads the first word into essay, then, as long as the eof marker is not set on the stream it echoes back the word just read, and then reads another word, overwriting the previous one.
Here's the correct code. Note that checking for eof in a loop condition is a bad idea, because it doesn't quite do what you want, and would also get you stuck in an infinite loop if the stream instead entered an error condition.
string word;
while (inputFile >> word) { // read a word and stop if this fails for any reason
essay += word;
essay += " ";
}
Though I'm not sure why you read the file word by word instead of all at once.
Also, I feel the need to repeat what M.M. said in a comment: your use of raw character arrays on input is unsafe and unnecessary. Just use string. You need to then write inputFile.open(inputFileName.c_str()) unless your standard library is new enough to have the string overloads of these functions, but that is fine. The other way of doing it is dangerous and a very bad habit to get into.
Try include cstring on top of string as well.
String is considered char array which is a more 'unique' way of storing data. You can try the code listed below.
int size = essay.length();

How to show contents of the file in C++

I have some code here
https://github.com/Fallauthy/Projects/blob/master/cPlusPlusProjects/bazaPracownikow/bazaPracownikow/bazaPracownikow/main.cpp
And I have no idea how to show contents in my file. I mean i know how, but it doesn't show same I Have in file (in link). It show in next line. This code is responsible to load file
while (!baseFile.eof()) {
//wczytaj zawartosc pliku do zmiennej
std::string buffer;
baseFile >> buffer;
//wypisz
loadLineFromBase += buffer;
loadLineFromBase += " \n";
}
std::cout << loadLineFromBase << std::endl;
Unless I see all your code all I can do for you is give you a sample in return, I don't know what you're trying to do but it seems in this case you're looking for this.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string Display = "";
ofstream FileOut;
ifstream FileInput;
FileOut.open("C:\\Example.txt");
FileOut << "This is some example text that will be written to the file!";
FileOut.close();
FileInput.open("C:\\Example.txt");
if (!FileInput)
{
cout << "Error File not Found: " << endl;
return 1;
}
while (!FileInput.eof())
{
getline(FileInput, Display);
}
FileInput.close();
cout << Display << endl;
return 0;
}
Simply put if you're currently working wit ha text document
use getline()
When you use getline() it takes two arguments the first will be in this case your ifstream object, as in what you're using to open the file. The second will be the string you're using to store the contents in.
Using the method I outlined above you'll be able to read the entire file contents.
And please next time as it was said above outline your problem more in depth and if you provide us with all of your code we may better assist you!
Your snippet of code automatically add a newline to every string read from the input file, even if originally those were words separeted by spaces. Probably you want to keep the structure of the original file, so it's better to read one line at a time and, unless you need it for some other uses, print it out in the same loop.
std::string buffer;
// read every line of baseFile till EOF
while ( std::getline(baseFile, buffer) ) {
std::cout << buffer << '\n';
}

Extract Information from colon seperated .txt file, C++

guys. I'm writing this small test program to read the text file from "EXAMPLE.txt" into my main program. At the output, I put "*" to displayed the data during the output is the data that I want to extract it out and locate into an array. Let say, in this test program the data that I wanted to extract is "JY9757AC", "AZ9107AC","GY9Z970C". But after that, I have did a try run and I faced this problem when comes to the output.
EXAMPLE.txt
ABC:JY9757AC
HDMI:AZ9107AC
SNOC:GY9Z970C
MAIN.CPP
main()
{
string output;
ifstream readExample;
readExample.open("EXAMPLE.txt");
while(readExample.eof())
{
getline(readExample,output,':');
cout << "* " << output <<endl;
}
}
OUTPUT
* ABC //while loop output the "ABC", which is the data that I don't want.
* JY9757AC
HDMI //it work's well, as what I expected and so and the SNOC below
* AZ9107AC
SNOC
* GY9Z970C
I have no any idea why is the "* ABC" is shown on the output, is there anything wrong with my logic. or I missed out something inside the while loop? Thank You in advance for helping to solve my code!
The delim parameter for getline replaces the default delimiter for new line which is "\n".
What you are currently getting as a "line" is:
ABC
JY9757AC\nHDMI
AZ9107AC\nSNOC
GY9Z970C
What you can do is more something like this (if your output like GY9Z970C) is fixed-size:
ssize_t len = getline(readExample,output,':');
cout << "* " << (char*)(output + (len - 8)) <<endl;
Output stores the first extraction from Example.txt and prints it followed by *. In the first iteration output = "ABC"; in the second iteration output = "JY9757AC";. I have added a getline() in the while loop that reads the unwanted part of the line. I also added a string[] to store the extracted values in.
#include <fstream>
#include <string>
using namespace std;
int main()
{
string output, notWanted, stringArray[3];
int i = 0;
ifstream readExample;
readExample.open("EXAMPLE.txt");
while (!readExample.eof())
{
getline(readExample, notWanted, ':');
getline(readExample, output);
cout << "* " << output << endl;
stringArray[i++] = output;
}
cin.get();
return 0;
}
First, I assume the while loop is while(!readExample.eof()), otherwise there should be no output at all.
Second, to your question, the first getline(readExample,output,':'); read "ABC" into the output, so at the next line it outputs * ABC, which is exactly what you got. No surprise.