Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Very newbie question

Status
Not open for further replies.

FredrikN

Programmer
Jan 5, 2001
60
0
0
SE
Hi, I'm new to C and I have a little problem with scanf funktion.

It seems that I only can get everything before a spece(if if exist) and the text after it.

eg

char text[30];
printf ("Enter some text");
scanf("%s", &text);
printf("\nYou wrote %s\n", text);


If I run this program och after the "Enter some text" prompt writes "Hello dude" it will only print out
"You wrote Hello"

How do I do if I want to print out all including the white spaces ??

Thanks

///Fredrik
 
Hello Fredrik!

I think the better function for getting a string in a variable is gets() which is included in <stdio.h>.

for example:

#include <stdio.h>

void main(){
char var[20];
printf(&quot;Enter some text: &quot;);
gets(var);
printf(&quot;%s&quot;,var);
}

But you must be careful with the length of var! It doesn´t matter how many whitespaces are in the input.

br maschwa
 
Hi maschwa.

I tried your code but I recived this warning:

/tmp/ccTduRFm.o: In function `main':
/tmp/ccTduRFm.o(.text+0x1e): the `gets' function is dangerous and should not be used.

It works fine with the whitespaces now, but what is the warning about ?
I'm using gcc 2.95.3

Thanks again

//Fredrik
 
Hi maschwa.

I tried your code but I recived this warning:

/tmp/ccTduRFm.o: In function `main':
/tmp/ccTduRFm.o(.text+0x1e): the `gets' function is dangerous and should not be used.

Maybee I only should use scanf ?

It works fine with the whitespaces now, but what is the warning about ?
I'm using gcc 2.95.3

Thanks again

//Fredrik
 
scanf(&quot;%s&quot;, &text);

do not pass the address of text, for a character array just use the name of the array:

scanf(&quot;%s&quot;, text);
 
Hi Fredrik!

I tried to compile with 16bit Borland-compiler and 32bit DeveloperStudio. There was no warning in both cases. I tried the code of jtm111 but it doesn´t work with whitespaces, too.

Br maschwa
 
You must use fgets();

type &quot;man gets&quot; (if on unix/linux), it will tell you why gets() is dangerous.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top