cin.get(char *, int, termination char) question
From: Peter Gordon (petergo_at__deleteme_.netspace.net.au)
Date: 02/28/05
- Previous message: Martijn Mulder: "Re: Character input leading to default of switch statement always"
- Next in thread: Robert W Hand: "Re: cin.get(char *, int, termination char) question"
- Reply: Robert W Hand: "Re: cin.get(char *, int, termination char) question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 28 Feb 2005 01:29:56 +0000 (UTC)
I am exploring the iostream get method
with three arguments. eg cin.get(buf, 80, ';')
My reference says, "If a termination character is
reached before the maximum number of characters is
read, a null is written and the termination character
is left in the buffer".
Using the above exampe, to me this means that if
a ';' is encountered before 79 characters are read,
the string in buf will be null terminated. The
reference does not mention empty fields.
eg. If the buffer being read contains
"abc;;def", how is the second field treated?
I wrote some test code and have compiled it with
both Cygwin g++ 3.3.3-3 and with bcc32, which is the
command line compiler for Borland CBuilder4.
They give different output. Thus, I am wondering
if I have found a bug in g++ or if since the reference
does not explicitly mention empty fields, the result is
undefined. Any thoughs on this?
I am working on Win XP and have tried it using bash from
Cygwin and the MKS Korn shell. Both give the same result.
The test file, called a.txt contains the line:
abc;;def;ghi;jkl
The command I give is:
get.compiler.test < a.txt
The output from the bcc32 compiled code is:
abc
Empty field
def
ghi
jkl
The output from the g++ compiled code is:
abc
In other words, g++ considers it an error.
My test code in the file "get.compiler.test.cpp" is:
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char *argv[]) {
char *pstr[10], ch;
int i, nfields;
for(i = 0; i < 10; ++i)
pstr[i] = new char(20);
nfields = 0;
for(i = 0; i < 10; ++i, ++nfields) {
if( ! cin.get(pstr[i], 20, ';'))
break;
cin.ignore(1, ';');
}
for(i = 0; i < nfields; ++i)
if( strlen(pstr[i]) )
cout << pstr[i] << endl;
else
cout << "Empty field" << endl;
return 0;
}
Be kind to me, it is only test code.
Peter Gordon
- Previous message: Martijn Mulder: "Re: Character input leading to default of switch statement always"
- Next in thread: Robert W Hand: "Re: cin.get(char *, int, termination char) question"
- Reply: Robert W Hand: "Re: cin.get(char *, int, termination char) question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]