c++ copying console values to a csv - c++

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.

Related

How to read back what I just wrote to a file?

I've been trying to write a program to open a file in both read and write mode:
#include <fstream>
#include <iostream>
using namespace std;
int main(){
fstream obj;
obj.open("hello.txt",ios::in|ios::out);
if (!obj){
cout << "File not opened" <<endl;
return 1;
}
obj << "Hi How are you" ;
char c;
while (!obj.eof()){
obj.get(c);
cout << c;
}
obj.close();
return 0;
}
When I compile this program on Visual Studio Code on Windows, though the text "Hi how are you" is printed in the file, the contents of the file are not printed on my screen. Can someone tell me what might be the problem?
Resetting the position indicator with seekp to 0 helps, because both output and input indicators are set to the end of file after write operation (you can read them with tellp tellg).
obj << "Hi How are you" ;
obj.seekp(0);
char c;
while (!obj.eof()){
obj.get(c);
cout << c;
}
Considering avoiding using obj.eof(), you can e.g. read your file line by line:
std::string line;
std::getline(obj, line);
std::cout << line << std::endl;
or in the loop:
while (std::getline(obj, line)) // here std::basic_ios<CharT,Traits>::operator bool is used to check if operation succeeded
{
std::cout << line << std::endl;
}
You got two problems there: buffering and seek position.
Buffering:
When you write the text with obj << "Hi How are you, you just write it into the buffer and the text gets written into the file after flushing the buffer. You can adjust which buffer type you want to use. The easiest way is to write std::endl after your text if you use line buffering.
A better explaination is already here
Seek Position:
You are reading from the last position in your file. You have to manually change the read position to the first character in the file, then you are done.

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.

How to print output in a file after a few empty lines

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.

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

write data at desired line in already existing file

I have a text file which already has 40 lines of data . I want to write data just before last two lines in a file. I am newbie to c++. I searched online and found few functions like fseek and seekp, but I am not getting how those those functions to change the lines. Can you please give some pointers for this?
Thank you in advance.
Open your file using a std::ifstream
Read the whole file into a std::vector<std::string> with an entry for each line in the file (you can use std::getline() and std::vector<std::string>::push_back() methods to realize this).
Close the std::ifstream
Change the vector entry at the line index you want to change, or alternatively insert additional entries to the vector using std::vector<std::string>::insert()
Open your file using a std::ofstream
Write the vectors content back to the file (just iterate over the vector and output each entry to the file).
You shouldn't mess around with seek functions in this case; particularly not, if the replacements size changes dynamically.
You say C++, so I assume you mean that and not C. A FIFO comes to mind for this purpose.
$ cat last_two_lines.c | ./a.out
#include <iostream>
#include <string>
#include <deque>
main ()
{
std::deque<std::string> fifo;
while (!std::cin.eof()) {
std::string buffer;
std::getline(std::cin, buffer);
fifo.push_back(buffer);
if (fifo.size() > 2) {
std::cout << fifo.front() << "\n";
fifo.pop_front();
}
}
std::cout << " // LINE INSERTED" << "\n";
while (fifo.size() > 0) {
std::cout << fifo.front() << "\n";
fifo.pop_front();
}
return 0;
// LINE INSERTED
}