473,738 Members | 4,774 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Ifstream problem

Iam new bie to C++ programming..

I want to write a program which will read the Comma separated
values(CSV) file column wise.

For example:
In a.txt:

"TicketNumber", "Phone","CarNum ber"
10,20,30
40,45,80
60,70,34

I want to read the values like the following:
"TicketNumb er",
10
40
60

and want to store in the values {10,40,60 } in an array.
When Iam compiling the below program in VC++ 6.0 i get the following
error:

d:\vs6\vc98\inc lude\vector(48) : warning C4786:
'??0?$vector@V? $basic_string@D U?$char_traits@ D@std@@V?$alloc ator@D@2@@std@@ V?$allocator@V? $basic_string@D U?$char_traits@ D@std@@V?$alloc ator@D@2@@std@@ @2@@std@@QAE@IA BV?$basic_strin g@DU?$char_trai ts@D@s
C:\test.cpp(269 ) : error C2059: syntax error : 'constant'
C:\test.cpp(271 ) : error C2065: 'status' : undeclared identifier
C:\test.cpp(288 ) : fatal error C1020: unexpected #endif
Error executing cl.exe.

test.obj - 12 error(s), 6 warning(s)
Could anyone help?

Regards
Ram Laxman


#include<fstrea m>
#include<ios>
#include <iostream>
#include<string >
#include<iomani p>
#include<sstrea m>
#include<vector >
#include<algori thm>
#include<stdio. h>
#include <fcntl.h>
#include <io.h>
#include <cstdlib>
#include <cstring>

using namespace std;

const char *filename ="C:\\result.tx t";

#define TRUE 1
#define FALSE 0
class test
{

public:
test(ifstream& fin = ifs) :
fin(ifs) {}
// test(ifstream& fin = filename) :
// fin(filename) { }

string read_file_heade r(string &str1, ifstream ifs);
int checkofcomma(ch ar c);
int checknextquote( string &line,string &fld,int i);
int checkofeol(char c,ifstream &ifs);
int commacount(char c,ifstream &ifs);
int getline(ifstrea m &ifs,string &line);
bool parseline(strin g &str,string &line);
/* string getfield(int n);
int getnfield() const { return nfield; } */

private:
ifstream& ifs; // input file pointer
string line; // input line
vector<string> field; // field strings
// int nfield; // number of fields
// string fieldsep; // separator characters

};

/* Read the Column Header from the file */
string test:: read_column_hea der(string &str1, ifstream ifs)
{
char *pdest;
int pos;
char lineone[256];
if (!ifs.eof())
{
ifs.getline(lin eone,sizeof(lin eone),'\n');
pdest =strstr(lineone ,str1);
while (pdest == 0)
{
ifs.getline(lin eone,sizeof(lin eone),'\n');
pdest = strstr(lineone, str1);
}
pos = pdest - lineone + str1.length();//end of Test:

string s = lineone;
string s1 = s.substr(0,pos) ; /* Return the SubString if the
matches found */
return s1;
}
else
{
return "EOF";
}
}
/* Check for \r or the \n in the line which was get by stream */
int test:: checkofeol(char c,ifstream &ifs)
{

int eol;
eol= (c=='\r' || c== '\n'|| c== ',') ;
if(c=='\t')
{
// continue; /* ignore tab spaces in the line */
}

if(c == '\r')
{

ifs.get(c);
if(!ifs.eof() && c != '\n')
ifs.putback(c);

}

return eol;
}
/* Count the number of comma in the line */
int test:: commacount(char c,ifstream &ifs)
{

int count=0;
for(line == "";ifs.get( c) && !checkofeol(c,i fs);)
{
if(c==',')
{
count++;
}

}

return count;

}

/* Get Next Quote and return the index of next quote */
int test:: checknextquote( string &line,string &fld,int i)
{

int j;
fld ="";
for(j=i;j<line. length();j++)
{
if(line[j] == '"' && line[++j] != '"')
{

int k =line.find_firs t_of('"',j);
if(k>line.lengt h())
k=line.length() ;
/* Store the String in an array */
for(k=k-j;k-- >0;)
fld=fld+line[j++];
break;

}

fld=fld+line[j];

}

return j;

}
/* This function return the position of the plain text or integer
which doesnot have quote */
int test:: checkplain(stri ng &line,string &fld,int i)
{

int j;
j=line.find_fir st_of(',',i); /* Look for separator */
if(j>line.lengt h())
j=line.length() ;
fld=string(s,i, j-i);
return j;

}

/* Get one line and tokenize based on the delimiter */
int test:: getline(ifstrea m &ifs,string &line)
{

char c;
for(line == "";ifs.get( c) && !checkofcomma(c );)
{
line =line+c;
}
//if(
str1=line;
return !ifs.eof();

}
/* Split each line of the field with the delimeter */
/* String line peakmemory,etc needs to be passed here */
bool test:: parseline(strin g &str,string &line)
{

int position=1;
/* int saveposition; */
string fld;
int i,j;
int nfield=0;
if(line.length( )==0)
return 0;
i=0;

do
{
if(i< line.length() && line[i] == '"')
{ /* get next position of quote */
j=checknextquot e(line,fld, ++i);
if(line[++j] == ',') /* If there is comma
after the position of quote
then go to new line */
{

position = position-line[j] +str.length();
/* Go to next line */
cout << "\n";
position=1; /* Go to First Position again */
}
}

else
{
j=checkplain(li ne,fld,i); /* In this function if there is no
quote then it will be integer
of prefixlength */
if(line[++j] == ',')
{
/* Update the position */
position =position -line[j]+str.length();
if(nfield >=field.size( ))
{
field.push_back (fld);
}
else
{
field[nfield]=fld;
}

}
/* Got to next line */
cout << "\n";
/* Reset the position */
position=1;
}

nfield ++;
i=j+1;

} while (j<line.length( ));

/*return nfield; */
return TRUE;

}

int main()
{

/* Create an object of test class */

int count;
char c;
bool success =FALSE;
const char *strprint;
int i;
//string tok1;
int result;
string s1,s2("ticketno "),s3("phonenum ber"),s4("carno ");

if 0
int status;
status = _open(filename, _O_RDONLY);
if(status == -1)
{
printf("Couldno t able to Open file ");
}
else
{
printf("Opening of file Successful\n");
}

ifstream ifs(filename); // Open for reading
if(ifs.fail())
{
cout << "Couldnot Open the stream";
return EXIT_FAILURE;

}
#endif

ifstream ifs(filename);
test test1;

while(test1.get line(ifs, s)) // Discards newline char(Read line by
line)
{

s += line + "\n";
strprint= s.data();

// cout << strprint << endl;
count=commacoun t(c,ifs);
for(i=0;i<=coun t;count++)
{
string str3= test1.read_colu mn_header(s2,if s);
result=str3.com pare(s2);
if (result == 0)
{
string str = str3;

}

string str4=test1.read _column_header( s3,ifs);
result =str4.compare(s 3);
if(result == 0)
{

string str =str4;

}

string str5 =test1.read_col umn_header(s4,i fs);
result=str5.com pare(s4);
if(result == 0)
{

string str =str5;

}

/* Parse Each line */
success = test1.parseline (str,line);

if(success)
printf("Parsing Successful");
}

if(!ifs && !ifs.eof())
cout << "Error in Reading Input file";
ifs.close();
// out.close();
return 0;

}
Jul 22 '05 #1
6 3392

"Ram Laxman" <ra********@ind ia.com> wrote in message
news:24******** *************** ***@posting.goo gle.com...
Iam new bie to C++ programming..

I want to write a program which will read the Comma separated
values(CSV) file column wise.

For example:
In a.txt:

"TicketNumber", "Phone","CarNum ber"
10,20,30
40,45,80
60,70,34

I want to read the values like the following:
"TicketNumb er",
10
40
60

and want to store in the values {10,40,60 } in an array.
When Iam compiling the below program

Oh my goodness! All that, just to pick out one item from the
start of each line? And what's that nonstandard <io.h>
and <fcntl.h> stuff for?

I've stored the data in a vector. You can copy it
to an array if you need.

#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

int main()
{
std::ifstream input("result.t xt");
if(!input)
{
std::cerr << "Cannot open input\n";
return EXIT_FAILURE;
}

std::vector<int > values;
std::string line;

while(std::getl ine(input, line))
{
std::istringstr eam iss(line);
int value(0);
iss >> value;
values.push_bac k(value);
}

std::copy(value s.begin(), values.end(),
std::ostream_it erator<int>(std ::cout, "\n"));

return 0;
}

Input file:
10,20,30
40,45,80
60,70,34
Output:
10
40
60
-Mike
Jul 22 '05 #2

"Ram Laxman" <ra********@ind ia.com> wrote in message
news:24******** *************** ***@posting.goo gle.com...
Iam new bie to C++ programming..

I want to write a program which will read the Comma separated
values(CSV) file column wise.

For example:
In a.txt:

"TicketNumber", "Phone","CarNum ber"
10,20,30
40,45,80
60,70,34

I want to read the values like the following:
"TicketNumb er",
10
40
60

and want to store in the values {10,40,60 } in an array.
When Iam compiling the below program in VC++ 6.0 i get the following
error:

d:\vs6\vc98\inc lude\vector(48) : warning C4786:
'??0?$vector@V? $basic_string@D U?$char_traits@ D@std@@V?$alloc ator@D@2@@std@@ V
?$allocator@V?$ basic_string@DU ?$char_traits@D @std@@V?$alloca tor@D@2@@std@@@ 2
@@std@@QAE@IABV ?$basic_string@ DU?$char_traits @D@s C:\test.cpp(269 ) : error C2059: syntax error : 'constant'
C:\test.cpp(271 ) : error C2065: 'status' : undeclared identifier
C:\test.cpp(288 ) : fatal error C1020: unexpected #endif
Error executing cl.exe.

[snip]

if 0


Here's your error, it should be

#if 0

but as Mike said this code is far, far too complicated. You are trying to do
a simple thing, the code should be simple too.

[snip]
Jul 22 '05 #3
The code also has many C-like stuff which shouldn't really be used in
C++ unless absolutely neccessary (imo). Like #define's, char arrays as
strings and printf are C-ways of doing things.

C++ has values false and true so you don't have to #define those, as in C.
Also you shouldn't #define's because they don't have any type-checking
of which C++ is so proud of; use constants instead.

And for the char arrays as strings... don't use them :)
Again, it's C-way of doing things and might get troublesome on the long
run. std::string is much better and easier to handle. std::string has a
function .c_str() which returns char* of the string so you can use it to
open a file.

There's no real reason to use printf() instead of cout; at least non
that I know of.

You should stick in to one style of programming in your program and not
use two equivalent things together in the same code since it might be
confusing to the readers.

Some people say that using 'using namespace std;' is bad, but I don't
think this shouldn't taken seriously before you've learned all the
basics and do some more complex stuff.

I'm not very good programmer myself, but these are just tips which I've
gotten from my university (first year) courses of programming; please
don't get offended.

- Jonne Lehtinen
Jul 22 '05 #4
Ram Laxman wrote:

Iam new bie to C++ programming..

I want to write a program which will read the Comma separated
values(CSV) file column wise.

For example:
In a.txt:

"TicketNumber", "Phone","CarNum ber"
10,20,30
40,45,80
60,70,34

I want to read the values like the following:
"TicketNumb er",
10
40
60

and want to store in the values {10,40,60 } in an array.

When Iam compiling the below program in VC++ 6.0 i get the following
error:

d:\vs6\vc98\inc lude\vector(48) : warning C4786:
'??0?$vector@V? $basic_string@D U?$char_traits@ D@std@@V?$alloc ator@D@2@@std@@ V?$allocator@V? $basic_string@D U?$char_traits@ D@std@@V?$alloc ator@D@2@@std@@ @2@@std@@QAE@IA BV?$basic_strin g@DU?$char_trai ts@D@s
C:\test.cpp(269 ) : error C2059: syntax error : 'constant'
C:\test.cpp(271 ) : error C2065: 'status' : undeclared identifier
C:\test.cpp(288 ) : fatal error C1020: unexpected #endif
Error executing cl.exe.

test.obj - 12 error(s), 6 warning(s)

Could anyone help?
it would be great if you could mark in the future what line 269 actually is.
This way I would not have to cut&paste your code into VC++, fix all the
line breaks just to be able to look up line 269

Here is the section around line 269:
if 0
int status;
status = _open(filename, _O_RDONLY);


what should that lonely if 0 be???
That's certainly not a C++ statment, or did you mean

#if 0

that would fit nicely with the #endif which comes later and
doesn't have a corresponding #if or #ifdef, which is
also indicated by one of the compilers error messages.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #5
Thanks a lot..But How I will retrieve the specific values based on the
header string from the file?.I thought of Map will do the needful.
Map<String("Tic ketNumber",Valu es(array)>.But I don't know how to use
it?
Can anybody help?

Karl Heinz Buchegger <kb******@gasca d.at> wrote in message news:<40******* ********@gascad .at>...
Ram Laxman wrote:

Iam new bie to C++ programming..

I want to write a program which will read the Comma separated
values(CSV) file column wise.

For example:
In a.txt:

"TicketNumber", "Phone","CarNum ber"
10,20,30
40,45,80
60,70,34

I want to read the values like the following:
"TicketNumb er",
10
40
60

and want to store in the values {10,40,60 } in an array.

When Iam compiling the below program in VC++ 6.0 i get the following
error:

d:\vs6\vc98\inc lude\vector(48) : warning C4786:
'??0?$vector@V? $basic_string@D U?$char_traits@ D@std@@V?$alloc ator@D@2@@std@@ V?$allocator@V? $basic_string@D U?$char_traits@ D@std@@V?$alloc ator@D@2@@std@@ @2@@std@@QAE@IA BV?$basic_strin g@DU?$char_trai ts@D@s
C:\test.cpp(269 ) : error C2059: syntax error : 'constant'
C:\test.cpp(271 ) : error C2065: 'status' : undeclared identifier
C:\test.cpp(288 ) : fatal error C1020: unexpected #endif
Error executing cl.exe.

test.obj - 12 error(s), 6 warning(s)

Could anyone help?


it would be great if you could mark in the future what line 269 actually is.
This way I would not have to cut&paste your code into VC++, fix all the
line breaks just to be able to look up line 269

Here is the section around line 269:

if 0
int status;
status = _open(filename, _O_RDONLY);


what should that lonely if 0 be???
That's certainly not a C++ statment, or did you mean

#if 0

that would fit nicely with the #endif which comes later and
doesn't have a corresponding #if or #ifdef, which is
also indicated by one of the compilers error messages.

Jul 22 '05 #6
"Ram Laxman" <ra********@ind ia.com> wrote in message
news:24******** *************** ***@posting.goo gle.com...
Thanks a lot..But How I will retrieve the specific values based on the
header string from the file?.I thought of Map will do the needful.
Map<String("Tic ketNumber",Valu es(array)>.But I don't know how to use
it?
Can anybody help?


First, please don't top-post.

I find your question rather vague. Here's my best guess:
/* (If a 'field' is 'missing' from a line, a default value is
stored (an empty string for the 'headers' or zero for the
integers) */

#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>

std::istream& get_headers(std ::istream& is,
std::vector<std ::string>& headers,
char delim = ',')
{
headers.clear() ;
std::string line;
std::string header;

if(std::getline (is, line))
{
std::istringstr eam iss(line);

while(std::getl ine(iss, header, delim))
headers.push_ba ck(header);
}

return is;
}

std::istream& get_values(std: :istream& is,
std::vector<int >& values,
char delim = ',')
{
values.clear();
std::string line;
std::string value;

if(std::getline (is, line))
{
std::istringstr eam iss(line);

while(std::getl ine(iss, value, delim))
{
std::istringstr eam iss(value);
int num(0);
iss >> num;
values.push_bac k(num);
}
}

return is;
}

void show_vec(std::o stream& os,
const std::vector<int >& v)
{
std::vector<int >::const_iterat or it(v.begin());
std::vector<int >::const_iterat or en(v.end());

while(it != en)
os << " " << *it++ << '\n';

std::cout << '\n';
}

void show_map(std::o stream& os,
const std::map<std::s tring, std::vector<int > >& m)
{
std::map<std::s tring, std::vector<int > >::const_iterat or it(m.begin());
std::map<std::s tring, std::vector<int > >::const_iterat or en(m.end());

while(it != en)
{
os << it->first << '\n';
show_vec(os, it->second);
++it;
}
}

int main()
{
std::ifstream input("result.t xt");
if(!input)
{
std::cerr << "Cannot open input\n";
return EXIT_FAILURE;
}

std::vector<std ::string> hdrs;
std::vector<int > vals;

std::map<std::s tring, std::vector<int > > data;

if(get_headers( input, hdrs))
while(get_value s(input, vals))
{
std::vector<int >::size_type val_count(vals. size());

for(std::vector <std::string>:: size_type i = 0; i != hdrs.size();
++i)
data[hdrs[i]].push_back(i < val_count ? vals[i] : 0);
}

show_map(std::c out, data);
return 0;
}
Input file:

"TicketNumber", "Phone","CarNum ber"
10,20,30
40,45,80
60,70,34

Output:

"CarNumber"
30
80
34

"Phone"
20
45
70

"TicketNumb er"
10
40
60

Exercises:
1) Try to refactor the 'get_headers()' and 'get_values()'
functions into a single function, using a template.

2) Write a function to strip the quotes off of the text strings
in the input file.
HTH,
-Mike
Jul 22 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
13779
by: Dave Johnston | last post by:
Hi, I'm currently trying to create a wrapper that uses C functions but behaves like ifstream (from fstream.h) - this is because the platform I'm using (WinCE) doesn't support streams and this is the easiest way to take a huge project across onto it. Basically, I've hit a problem. I have no idea how the ifstream class handles directories. In the code I have (which I didn't write), there are several places whereby an ifstream stream is...
1
2369
by: Jim Phelps | last post by:
Hello all, I am in a bit of a pickle using the getline function with an ifstream. It does not seem to work as advertised. Here is my scenario. In a nutshell, my code needs to pick up a fixed record length flat file that is generated by an old IBM mainframe. These data fields need to be read in by my program EXACTLY as they are represented in the file. Here is an example text file that I used in my test. ...
4
3736
by: hall | last post by:
Hi. I ran across a bug in one of my problems and after spending some time tracking it down i found that the problem arose in a piece of code that essentially did this: ----------- ifstream in("in.txt"); if(!in) {cout << "error\n";} in.close(); if(!in) {cout << "error\n";} in.close(); if(!in) {cout << "error\n";}
1
6252
by: inkapyrite | last post by:
Hi all. I'm using ifstream to read from a named pipe but i've encountered an annoying problem. For some reason, the program blocks on reading an ifstream's internal buffer that's only half-filled. Only when the buffer becomes full does it resume execution. Here's my test code for reading from a pipe: //(compiled with g++ -std=c++98) //--------------------------------------------- #include <iostream>
10
18003
by: sam | last post by:
Hi, Can anyone tell me how to print a file name from ifstream? the following cout code does not print the filename I created with ifstream preivous: ifstream is; is.open ("text.txt");
3
7238
by: toton | last post by:
Hi, I want to unread a few things while I am reading a file. One solution I know is putback the characters read to the buffer. But as I need frequent moving file pointer , to a few steps back, I was thinking of seekg & tellg function. But it is not workings as I expect.... here is the test code, std::string word; std::string value;
1
5013
by: SantaClaus | last post by:
Hi all, Im getting an exception in the middle of reading a file and here is my code std::ifstream inf; const int bufSize=1024; char tbuffer; std::string filex = path; // may be C:\test.txt const char* stx = &filex; inf.open(stx,ios_base::in|std::ios::binary); if(!inf.good()) { inf.clear();
7
3228
by: Boltar | last post by:
Hi I'm using ifstream (which I hardly ever use) to read an ascii text file (containing numbers delimited by newlines) in a loop using something like: ifstream infile("filename") int value; infile >value;
2
15304
by: mpalomas | last post by:
Hi C++ folks, I have trouble to open files whose path contains non-ascii characters with std::ifstream. For instance let's say i just have a file which has Japanese characters either in the file path or the file name : 疑問.dat. The file itself does not contains unicode characters or whatever, it is a binary file, but the file name, or path, contains non-ascii characters, here it is Japanese but it could be anything else, i know...
0
8788
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9476
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9335
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9208
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6751
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6053
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3279
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2745
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.