Trouble reading .csv files in C++ - c++

I am working on a project where I intend on connecting to a database, grabbing a .csv file, reading it, manipulating the data and then returning it back to the database. Fairly simple and straight forward but I am still learning so if any one could point me in the right direction I would greatly appreciate it. Right now I have a simple program that is trying to read a .csv file and return the values to me printed on the console. I have been trying to find some good online resources for this but have came up short. Here is my code for what I have stumbled through so far.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
int loop = 1;
while(loop = 1)
{
cout << "Welcome! " << endl;
ifstream myfile;
myfile.open ("..\\ Source\External\\ Sample.csv", ifstream::in);
The real path to this file is C:\Documents and Settings\RHatfield\My Documents\C++\Product Catalog Creator\Source\External\Sample.csv
while (myfile.good())
cout << (char) myfile.get();
myfile.close();
system("PAUSE");
return 0;
}
}
Now the issue is it does not print the values so I do not know that they are properly being captured. I have a feeling it is my file path but that's the only way I can find to write it without it throwing errors. I think it's something with the spaces in the file path but I can't seem to find another way to make it work. I am not looking for a handout and this is not homework or just regular work. I am trying to learn and having trouble teaching myself so if someone knows what the issue is and can help me fix it or even point me to a relevant article online would be greatly appreciated.

Try the following code. I think the problem was you were making an assignment statement in the while condition statement.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
cout << "Welcome! " << endl;
ifstream myfile;
myfile.open ("C:\\Documents and Settings\\RHatfield\\My Documents\\C++\\Product Catalog Creator\\Source\\External\\Sample.csv", ifstream::in);
while (myfile.good())
cout << (char) myfile.get();
myfile.close();
system("PAUSE");
return 0;
}

Related

Issues reading floats from .txt file

I am trying to read a .txt file with some floats into my code.
I wrote a sample code just to tackle the issue outside my main code and I am using the following floats to test it:
10.8f
100.8f
-10.8f
The issue I am running into is that the code only reads in the first float properly and displays it but all the other floats following it do not look correct:
10.8
0
4.57874e-41
Code:
#include<fstream>
#include<iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
float Cam1,Cam2,Cam3;
string path = "sample.txt"; //Text file with above mentioned floats
ifstream fin;
fin.open(path);
if(fin.is_open())
{
fin >> Cam1;
fin >> Cam2;
fin >> Cam3;
fin.close();
}
cout << Cam1 << '\n';
cout << Cam2 << '\n';
cout << Cam3 << '\n';
}
I really am confused as to why it reads the first properly but not the others, it works when I change the values as well, the above is just one example case. I am fairly new to C++ so any help would be greatly appreciated thank you!
The f suffix is valid in C++ code, but not in input text parsed by istream. It's useful in code to distinguish between float and double constants, but user input doesn't control variable data types.

After adding a function to use a renamed file, the program won't find the text string anymore

Okay, the title may be a bit vague. I honestly don't even know how to phrase the question.
The program tries to find a string of text inside a file, and then
print the entire line that the string is on.
While testing, I created a file with the string I wanted to find as the only contents of the file:
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <iostream>
#include <filesystem>
#include <Wininet.h>
#include <stdio.h>
//...
std::cout << "Creating a document...\n"; //this is test code that creates a sample document with "string" inside it.
std::ofstream write;
write.open ("test.txt"); //actual file creation
write << "[TEMPORARY]string[TEST]\n"; //print into the document
write.close();
std::cout << "Document created.\n"; //end message
When I use this configuration, the program finds "string" and outputs
[TEMPORARY]string[TEST] as expected.
However, this layout was only to be used in testing, so after confirming it worked, I wanted to test renaming the file that I would actually be using in order to find the same string.
I copied the file, and wrote a program to rename it to a text file so it would be easier to read from:
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <iostream>
#include <filesystem>
#include <Wininet.h>
#include <stdio.h>
//...
std::cout << "Changing extension to txt...\n";
//int result; //making variable to store result of following code. potential warning fix.
char oldname[] = "data.ldb"; //set up rename variables
char newname[] = "string.txt"; //same as ^
rename(oldname, newname); //change the ldb to txt so we can read from it.
std::cout << "Extension changed.\n"; //this code block produces a warning. please fix. low priority.
If changing ldb to txt is a stupid idea and won't work, let me know of any workarounds.
After I did this, the program does not find the string. Opening the file with notepad as an ldb or a txt shows the string exists.
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <iostream>
#include <filesystem>
#include <Wininet.h>
#include <stdio.h>
//...
std::cout << "Attempting to get line with word \"string...\"\n";
std::ifstream input; //"input" is what we are using to read the file.
size_t pos; //size_t has something to do with finding text.
std::string line; //this is what we save the line to.
input.open("string.txt"); //open the document with the string.
if (input.is_open()) { //if we are in the file...
while (!input.eof()) { //get a line from it..."
getline(input, line);
pos = line.find("string"); //that says "string."
if (pos != std::string::npos) { //if we find it...
std::cout << "Line found!" //print "Line found!"
" \n" //(this is to remove the "i couldn't find it" message.)
"The line is...\n\n";
std::cout << line; //and then print the line we found.
std::cout << "\n\nSaving to file...\n";
std::ofstream grab; //now open a new file...
grab.open("grabbedstring.txt"); //called "grabbedstring,"
grab << line; //print the line to it,
grab.close(); //and close the file.
std::cout << "Saved to file \"grabbedstring.txt"; //We did it! :D
}
else {
std::cout << "I couldn't find it, sorry.\n" //we didn't do it... D:
"\x1b[A";
}
}
}
else {
std::cout << "I couldn't open the file, sorry.\n"; //we didn't even come close... ;-;
}
input.close();
std::cout << "\n\nEnd of code so far.\n"
"Completed successfully!\n";
system("pause");
The program outputs "I couldn't find it, sorry.\n".
Honestly, I think it has something to do with the file conversion as it works with a text file created within the program itself, but i don't see much wiggle room there.
When I open the new text file in a text editor after the program fails, it works just fine.
EDIT:
After further testing, this might be situational. I created a sample ldb file with a string in it, and it worked. I tried pushing it way down to the bottom and it worked. I tried the original file, and it doesn't. it might actually just be unable to print some of the characters that are in the file. This may require a very complicated workaround, and it may even be impossible; or, it could be simple...I don't know. I will conduct further testing and if I solve the problem I will close the question.
It also doesn't save to the document, so it must be a problem within the if statement.
EDIT2: updated code, still not working. further testing concludes it might be a problem with the way the source file... well... is. it might be too long, it might be too complex, it might be impossible. i am seriously puzzled with this one. the code works fine in any other situation, so if you need something similar feel free to grab this and use it while i try and make it work for what I need.
oh yeah and thanks for the formatting, casey.

Ifstream is opening the file, but doesn't output the lines inside the file

Im new to c++ and i was trying to open a ".txt" file using ifstream. the file im using is called "ola.txt" which literally just contains two lines of text without punctuation just plain and simple text. The code that i wrote is this
#include <iostream>
#include <vector>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int x;
string line;
vector<int> vect;
ifstream inFile("C:\\Users\\ruial\\Desktop\\ola.txt");
inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt");
if (inFile.is_open()) {
while (getline(inFile, line))
{
cout << line << '\n';
}
inFile.close();
}
else {
cout << "Unable to open file";
exit(1); // terminate with error
}
return 0;
}
The path to the file that i wrote is correct such that the file opens, but when the program runs it doesn´t cout the lines that i wrote on the txt file to the cmd, i dont know if this is somewhat important but im coding in visual studio 2019.
I can't seem to find the answer to this problem anywhere in the internet and to be honest i think im doing it right, any help would be much appreciated,thanks in advance.
You are trying to open the inFile twice. First time during inFile construction, ifstream inFile("C:\\Users\\ruial\\Desktop\\ola.txt"), second time you try to open it again with inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt"), when it's already open, which is erroneous, and flags the stream as no longer good.
3 possible fixes:
Remove inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt")
Use default constructor, without specifying the file name
inFile.close() before you open it again (obviously, not the nicest fix).

Reading input from a text file and outputting the text to the screen in c++

I'm a new student of the c++ language and I'm having trouble understanding...well, frankly, a whole lot of things. I've been given this assignment to read text from a text file and output it to the screen, and I'm having quite a bit of trouble. I've spent several hours on this now already researching and testing, and this is the code that I've got so far, and it's not working, and I'm not really sure why. Any and all help or insights anyone would be willing to share with me would be very much appreciated. I'm sorry I don't recall all the errors I've encountered as I worked on this by name...but I assure you there were plenty of them. Like trying to use "fopen" in my compiler...it didn't like that, so I tried "fopen_s" like it suggested, but then it said that it wouldn't accept any arguments anymore...then I found that I needed to add "#define _CRT_SECURE_NO_DEPRECATE" as a header(?) file at the top of the program, and that problem did get solved and the program actually compiled...but then it gave me a fatal error, not sure what I did that was so fatal, but there you are. Please help.
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *pf;
char ch;
pf = fopen("C:\\lowerCase\anyOldTextFile.txt", "r");
feof(pf);
if (pf == NULL)
{
printf("Unable to open the file.\n");
}
else
{
while (!feof(pf))
{
ch = fgetc(pf);
printf("%c", ch);
}
fclose(pf);
}
system("pause");
}
Try this, which I pasted from this site:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
I didn't test this code, but it looks fine. They also explain the code on the website. I suggest visiting that page and reading all of it. Then you should be able to understand how this is working.

Problem with file stream/fstream in Xcode C++

Here is a simple program to output to a text file:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
double myNumber = 42.5;
fstream outfile("test.txt", fstream::out);
outfile << "The answer is almost " << myNumber << endl;
outfile.close();
}
All that ends up being wrote to my text file is, "The answer is almost " and the data is not displayed at all. What am I doing wrong? or could it be a problem with Xcode since I am using that as an IDE.
I'm not sure what the problem is. Is it that it's never executed or that it's writing to the wrong path. To shed light on this try include unistd.h and insert this snippet.
char* s = getcwd(NULL, 256);
printf("im running and pwd is: %s\n", s);
Inside xcode hit CMD-SHIFT-R to open the console and see if it prints anything.
There is no problem with your code. It could be a problem with Xcode.