473,545 Members | 2,021 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reading a string of unknown size

I have to read characters from stdin and save them in a string. The
problem is that I don't know how much characters will be read.

Francesco
--
-------------------------------------

http://www.riscossione.info/
Nov 25 '06 #1
111 19935
Tonio Cartonio said:
I have to read characters from stdin and save them in a string. The
problem is that I don't know how much characters will be read.
http://www.cpax.org.uk/prg/writings/fgetdata.php
http://cbfalconer.home.att.net/download/ggets.zip
http://www.iedu.com/mrd/c/getsm.c
http://storm.freeshell.org/anysize.c

Take your pick.

(Coming soon - Eric Sosman's equivalent, if he can remember to attach it to
the email this time...)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Nov 25 '06 #2
Tonio Cartonio wrote:
I have to read characters from stdin and save them in a string. The
problem is that I don't know how much characters will be read.
You'll have to read the input, either character-at-a-time, (using
getc() or fgetc()), or line at a time, (using fgets()), and store them
into a block of memory which can be dynamically resized as you read in
more input.

It's fairly easy to do this yourself, but if you want to use an already
available one, try CBFalconer's ggets() function. Search the group's
archive. The URL is mentioned quite regularly.

Nov 25 '06 #3
I have to read characters from stdin and save them in a string. The
problem is that I don't know how much characters will be read.
int main()
{
char *str = NULL, ch ;
int i = 0 ;
str = (char*) malloc (2*sizeof(char) ) ;
*str = '\0' ;

while( (ch=getchar()) != '\n' )
{
*(str+i) = ch ;
i++ ;
str = (char*) realloc(str, (2*sizeof(char) ) + i ) ;
}
*(str+i) = '\0' ;

printf("\n\n %s ", str) ;

getch() ;
return 0;
}
:)
--
Regards
Santosh S Nayak
E-Mail - sa***********@g mail.com
WebPage -- http://santoshsnayak.googlepages.com

Nov 27 '06 #4
Santosh said:
>I have to read characters from stdin and save them in a string. The
problem is that I don't know how much characters will be read.

int main()
{
char *str = NULL, ch ;
int i = 0 ;
str = (char*) malloc (2*sizeof(char) ) ;
Here is your first bug.
*str = '\0' ;
Here's the second.
>
while( (ch=getchar()) != '\n' )
Here's the third.
{
*(str+i) = ch ;
i++ ;
str = (char*) realloc(str, (2*sizeof(char) ) + i ) ;
Here's the fourth and fifth, at least.
}
*(str+i) = '\0' ;

printf("\n\n %s ", str) ;
Here's your sixth.
>
getch() ;
And your seventh.
return 0;
}
:)
In fourteen lines of code (excluding spaces and braces), you managed at
least seven bugs. What are you smiling about?

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Nov 27 '06 #5
:)In fourteen lines of code (excluding spaces and braces), you managed at
least seven bugs. What are you smiling about?
The program works correctly.

No offence pal, but make sure you are at least 10% right before you
reply to any post.

Nov 27 '06 #6
Santosh said:
:)In fourteen lines of code (excluding spaces and braces), you managed
:at
least seven bugs. What are you smiling about?

The program works correctly.
Really? Let's explore that, shall we?

foo.c:2: warning: function declaration isn't a prototype
foo.c: In function `main':
foo.c:3: `NULL' undeclared (first use in this function)
foo.c:3: (Each undeclared identifier is reported only once
foo.c:3: for each function it appears in.)
foo.c:5: warning: implicit declaration of function `malloc'
foo.c:5: warning: cast does not match function type
foo.c:8: warning: implicit declaration of function `getchar'
foo.c:12: warning: implicit declaration of function `realloc'
foo.c:12: warning: cast does not match function type
foo.c:16: warning: implicit declaration of function `printf'
foo.c:18: warning: implicit declaration of function `getch'
make: *** [foo.o] Error 1

Oh, look - it doesn't even compile.
No offence pal, but make sure you are at least 10% right before you
reply to any post.
I was 100% right that your program was a good 50% wrong (in terms of bugs
per line). And it doesn't compile on my system. If it compiles on yours
without generating at least one diagnostic message, then your compiler is
broken.

Furthermore, the OP did not indicate his platform (nor was there any need
for him to do that), let alone his implementation, so you can't just claim
"it works on *my* system", since there is no indication whatsoever that the
OP's system is the same as your system.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Nov 27 '06 #7
Santosh wrote:
I have to read characters from stdin and save them in a string. The
problem is that I don't know how much characters will be read.
First include necessary headers: stdio.h, stdlib.h
int main()
Better yet, replace above with int main(void)
{
char *str = NULL, ch ;
int i = 0 ;
str = (char*) malloc (2*sizeof(char) ) ;
Don't cast return value of malloc() in C. It can hide the non-inclusion
of it's prototype, (by way of failure to include stdlib.h), and, on
some implementations , can result in nasty crashes during runtime.

Since sizeof(char) is by definition 1, you can omit that and instead do
'2 * sizeof *str'. This has the advantage of becoming automatically
updated when you later on happen to change the type of *str.
*str = '\0' ;
And now you're possibly writing to a random area of memory, since you
failed to check the return value of malloc() above for failure.
while( (ch=getchar()) != '\n' )
Check for EOF not newline. Moreover getchar() returns an int value
which you're storing in a char variable, probably getting a spurious
garbage return value when end-of-file is encountered.
{
*(str+i) = ch ;
You've overwritten your earlier nul character.
i++ ;
str = (char*) realloc(str, (2*sizeof(char) ) + i ) ;
Again, _don't_ cast the return value of XXalloc() functions in C, and
check the call for failure before proceeding further. Also change
sizeof(char) to sizeof *str.

Anyway, your allocation strategy is very inefficient. Your calling
realloc() once every iteration of the loop. This could result in
fragmentation of the C library's memory pool. Why not allocate in terms
of fixed sized or dynamically growing blocks, say 128 bytes or so to
start with?
}
*(str+i) = '\0' ;

printf("\n\n %s ", str) ;
Unless you terminate the output with a newline character, it's not
guaranteed to show up on screen, or wherever stdout happens to be
directed to.
getch() ;
Non-standard, unportable and unnecessary function. Just get rid of it.

Nov 27 '06 #8
per line). And it doesn't compile on my system. If it compiles on yours
without generating at least one diagnostic message, then your compiler is
broken.

Furthermore, the OP did not indicate his platform (nor was there any need
for him to do that), let alone his implementation, so you can't just claim
"it works on *my* system", since there is no indication whatsoever that the
OP's system is the same as your system.
Do not get too excited and offensive, you forgot to include the
following files:
#include <stdio.h>
#include <conio.h>

If you are using a Unix system:
#include <stdio.h>
#include <sys/types.hOR #include <system.h>

Nov 27 '06 #9
Santosh said:
>per line). And it doesn't compile on my system. If it compiles on yours
without generating at least one diagnostic message, then your compiler is
broken.

Furthermore, the OP did not indicate his platform (nor was there any need
for him to do that), let alone his implementation, so you can't just
claim "it works on *my* system", since there is no indication whatsoever
that the OP's system is the same as your system.

Do not get too excited and offensive,
I am neither excited nor offensive.
you forgot to include the
following files:
#include <stdio.h>
#include <conio.h>
No, I didn't forget: you did.

And C offers no header named <conio.h>
If you are using a Unix system:
#include <stdio.h>
#include <sys/types.hOR #include <system.h>
Wrong. That wouldn't help your program compile.

Furthermore, even with the inclusion of those headers, your program is still
broken in several important ways.

I suggest you stop defending and start thinking.

The Other Santosh has given a good analysis of some of the problems with
your program. If you don't understand that analysis, start asking
intelligent questions instead of acting all defensively.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Nov 27 '06 #10

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

Similar topics

7
2764
by: jamait | last post by:
Hi all, I m trying to read in a text file into a datatable... Not sure on how to split up the information though, regex or substrings...? sample: Col1 Col2 Col3 Col4 A0012430 REKAL TVÄTTMEDEL EKOMAX 0,5L ST 75.9000
19
10277
by: Lionel B | last post by:
Greetings, I need to read (unformatted text) from stdin up to EOF into a char buffer; of course I cannot allocate my buffer until I know how much text is available, and I do not know how much text is available until I have read it... which seems to imply that multiple reads of the input stream will be inevitable. Now I can correctly...
3
3484
by: syntax | last post by:
hi, i want to read a file using fread() in equal chunks through a for loop so that at the last call i dont get error..which way, i should read it? let me give an example, suppose i have 100 chars, i can read it in 50 chars for twice or 10 chars in ten times or 25 chars for 4 times...like this. Here, file size, i.e 100 chars is known to...
6
3404
by: dough | last post by:
Heres a snippet of my code. I am trying to dynamically allocate memory for reading in strings from a file. FILE *f; /* file to read */ char *s; /* string being read */ f = "somefile.txt"; s = malloc(sizeof(char*)); /* allocates mem of string */ while( fscanf(f, "%s", s) !=...
2
2259
by: Chuck Ritzke | last post by:
Hi all, I am getting an intermittant error after uploading a project from my development machine. I click on a link which opens an aspx page that, upon page load, reads a very small amount of data from an MS Access database, using ODBC and a stored query. There is no problem on my development machine. On the production server though, I get...
10
26576
by: sposes | last post by:
Im very much a newbie but perhaps somehone can help me. Ive been searching for a way to convert a std::string to a unsigned char* The situation is I have a function that wants a unsigned char* and I want to give it a std::string no matching function for call to `MD5::update(std::string&, size_t)' candidates are: void MD5::update(unsigned...
9
4594
by: dgleeson3 | last post by:
Hello All I have a txt file of strings of different lengths. I dont know how many strings are in the file. I have no problem reading the file and sending to the console (as below). To store the strings read, in a buffer, I had decided to use an array of strings.
3
6697
by: cppman | last post by:
Hello, I am very new to C++ programming. I am trying to read a file with very large strings back to back, no commas or any other seperations between characters in a string and the size of the string is not known as well. I need to count how many characters totoal in a unknown size of a string. this is what I have so far: #include...
6
2770
by: diegoblin | last post by:
hello, i have this issue.Every time i use sockets if i use a "String" as a parameter the connection resets. but if i put the ip address like this "127.0.0.1" it okay. and i got this message if i use a string i read from the console Exception in thread "main" java.net.SocketException: Connection r at...
0
7664
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. ...
1
7436
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7766
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...
0
5981
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5341
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...
0
4958
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...
0
3446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1897
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
1
1022
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.