Mar 23rd, 2018, 04:38 PM
#1
Thread Starter
Member
[RESOLVED] taking out commas and quotations out of text file using c++
here is the code im using, it is executing with out errors but not getting any desired results
Code:
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
ifstream fin;
fin.open("C:\\Users\\rr296749\\Desktop\\mycorpus.txt", ios::in);
char my_character;
int number_of_lines = 0;
while (!fin.eof()) {
fin.get(my_character);
cout << my_character;
if (my_character == ',') {
my_character = ' ';
}
if (my_character == '"') {
my_character = ' ';
}
}
cout << my_character ;
Im tring to take this filemycorpus.txt and remove all the quotation marks and commas so i can use it in tableau
Mar 23rd, 2018, 08:10 PM
#2
Re: taking out commas and quotations out of text file using c++
You have zero code in place to actually write anything back to a file.
Not tested, but something like this should work:
Code:
ifstream fin;
ofstream fout;
fin.open("C:\\Users\\rr296749\\Desktop\\mycorpus.txt", ios::in);
fout.open("C:\\Users\\rr296749\\Desktop\\mycorpusNew.txt", ios::out);
char my_character;
int number_of_lines = 0;
while (!fin.eof()) {
fin.get(my_character);
cout << my_character;
if (my_character == ',') {
my_character = ' ';
}
if (my_character == '"') {
my_character = ' ';
}
fout << my_character;
}
cout << my_character ;
fout.close();
Mar 24th, 2018, 06:19 AM
#3
Re: taking out commas and quotations out of text file using c++
If it is required to change the contents of the file, rather than create a new one, consider
Code:
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
const string filnam = "mycorpus.txt";
int main()
{
const string chars = "\",";
const char repchar = ' ';
fstream fs(filnam, ios::binary | ios::in | ios::out);
if (!fs.is_open()) {
cout << "Cannot open file " << filnam << endl;
return 1;
}
while (fs)
if (chars.find(fs.peek()) == string::npos)
fs.get();
else {
fs.seekp(fs.tellg());
fs.put(repchar);
fs.seekg(fs.tellp());
}
fs.close();
}
This would change
Code:
a,,,b,c
,,c,dd,f,
ddddddd,ffffffffffff
to
Code:
a b c
c dd f
ddddddd ffffffffffff
as required.
PS The altered file is attached.
Attached Files
Last edited by 2kaud; Mar 24th, 2018 at 06:32 AM .
Reason: PS
All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain
https://creativecommons.org/publicdomain/zero/1.0/
C++23 Compiler: Microsoft VS2022 (17.6.5)
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Click Here to Expand Forum to Full Width