473,222 Members | 1,667 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,222 software developers and data experts.

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","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
6 3344

"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

"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
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","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
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
"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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
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...
1
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...
4
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...
1
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....
10
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
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...
1
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...
7
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; ...
2
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...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

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.