By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,020 Members | 1,297 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,020 IT Pros & Developers. It's quick & easy.

Ifstream problem

P: n/a
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","CarNumber"
10,20,30
40,45,80
60,70,34

I want to read the values like the following:
"TicketNumber",
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\include\vector(48) : warning C4786:
'??0?$vector@V?$basic_string@DU?$char_traits@D@std @@V?$allocator@D@2@@std@@V?$allocator@V?$basic_str ing@DU?$char_traits@D@std@@V?$allocator@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.

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

Regards
Ram Laxman


#include<fstream>
#include<ios>
#include <iostream>
#include<string>
#include<iomanip>
#include<sstream>
#include<vector>
#include<algorithm>
#include<stdio.h>
#include <fcntl.h>
#include <io.h>
#include <cstdlib>
#include <cstring>

using namespace std;

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

#define TRUE 1
#define FALSE 0
class test
{

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

string read_file_header(string &str1, ifstream ifs);
int checkofcomma(char c);
int checknextquote(string &line,string &fld,int i);
int checkofeol(char c,ifstream &ifs);
int commacount(char c,ifstream &ifs);
int getline(ifstream &ifs,string &line);
bool parseline(string &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_header(string &str1, ifstream ifs)
{
char *pdest;
int pos;
char lineone[256];
if (!ifs.eof())
{
ifs.getline(lineone,sizeof(lineone),'\n');
pdest =strstr(lineone,str1);
while (pdest == 0)
{
ifs.getline(lineone,sizeof(lineone),'\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,ifs);)
{
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_first_of('"',j);
if(k>line.length())
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(string &line,string &fld,int i)
{

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

}

/* Get one line and tokenize based on the delimiter */
int test:: getline(ifstream &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(string &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=checknextquote(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(line,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("phonenumber"),s4("carno");

if 0
int status;
status = _open(filename,_O_RDONLY);
if(status == -1)
{
printf("Couldnot 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.getline(ifs, s)) // Discards newline char(Read line by
line)
{

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

// cout << strprint << endl;
count=commacount(c,ifs);
for(i=0;i<=count;count++)
{
string str3= test1.read_column_header(s2,ifs);
result=str3.compare(s2);
if (result == 0)
{
string str = str3;

}

string str4=test1.read_column_header(s3,ifs);
result =str4.compare(s3);
if(result == 0)
{

string str =str4;

}

string str5 =test1.read_column_header(s4,ifs);
result=str5.compare(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
Share this Question
Share on Google+
6 Replies


P: n/a

"Ram Laxman" <ra********@india.com> wrote in message
news:24**************************@posting.google.c om...
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","CarNumber"
10,20,30
40,45,80
60,70,34

I want to read the values like the following:
"TicketNumber",
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.txt");
if(!input)
{
std::cerr << "Cannot open input\n";
return EXIT_FAILURE;
}

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

while(std::getline(input, line))
{
std::istringstream iss(line);
int value(0);
iss >> value;
values.push_back(value);
}

std::copy(values.begin(), values.end(),
std::ostream_iterator<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

P: n/a

"Ram Laxman" <ra********@india.com> wrote in message
news:24**************************@posting.google.c om...
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","CarNumber"
10,20,30
40,45,80
60,70,34

I want to read the values like the following:
"TicketNumber",
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\include\vector(48) : warning C4786:
'??0?$vector@V?$basic_string@DU?$char_traits@D@std @@V?$allocator@D@2@@std@@V
?$allocator@V?$basic_string@DU?$char_traits@D@std@ @V?$allocator@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

P: n/a
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

P: n/a
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","CarNumber"
10,20,30
40,45,80
60,70,34

I want to read the values like the following:
"TicketNumber",
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\include\vector(48) : warning C4786:
'??0?$vector@V?$basic_string@DU?$char_traits@D@std @@V?$allocator@D@2@@std@@V?$allocator@V?$basic_str ing@DU?$char_traits@D@std@@V?$allocator@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.

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

P: n/a
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("TicketNumber",Values(array)>.But I don't know how to use
it?
Can anybody help?

Karl Heinz Buchegger <kb******@gascad.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","CarNumber"
10,20,30
40,45,80
60,70,34

I want to read the values like the following:
"TicketNumber",
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\include\vector(48) : warning C4786:
'??0?$vector@V?$basic_string@DU?$char_traits@D@std @@V?$allocator@D@2@@std@@V?$allocator@V?$basic_str ing@DU?$char_traits@D@std@@V?$allocator@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.

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

P: n/a
"Ram Laxman" <ra********@india.com> wrote in message
news:24**************************@posting.google.c om...
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("TicketNumber",Values(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::istringstream iss(line);

while(std::getline(iss, header, delim))
headers.push_back(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::istringstream iss(line);

while(std::getline(iss, value, delim))
{
std::istringstream iss(value);
int num(0);
iss >> num;
values.push_back(num);
}
}

return is;
}

void show_vec(std::ostream& os,
const std::vector<int>& v)
{
std::vector<int>::const_iterator it(v.begin());
std::vector<int>::const_iterator en(v.end());

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

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

void show_map(std::ostream& os,
const std::map<std::string, std::vector<int> >& m)
{
std::map<std::string, std::vector<int> >::const_iterator it(m.begin());
std::map<std::string, std::vector<int> >::const_iterator en(m.end());

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

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

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

std::map<std::string, std::vector<int> > data;

if(get_headers(input, hdrs))
while(get_values(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::cout, data);
return 0;
}
Input file:

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

Output:

"CarNumber"
30
80
34

"Phone"
20
45
70

"TicketNumber"
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 discussion thread is closed

Replies have been disabled for this discussion.