Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to input a string using scanf in c including whitespaces

Tags:

c

Example if user enters:

My name is James.

Using scanf, I have to print the full line, i.e. My name is James., then I have to get the length of this entered string and store it in an int variable.

like image 990
shobhnit Avatar asked Feb 20 '11 00:02

shobhnit


2 Answers

Try:

scanf("%80[^\r\n]", string);

Replace 80 with 1 less that the size of your array. Check out the scanf man page for more information

like image 141
Splat Avatar answered Nov 12 '22 18:11

Splat


@Splat has the best answer here, since this is homework and part of your assignment is to use scanf. However, fgets is much easier to use and offers finer control.

As to your second question, you get the length of a string with strlen, and you store it in a variable of type size_t. Storing it in an int is wrong, because we don't expect to have strings of -5 length. Likewise, storing it in an unsigned int or other unsigned type is inappropriate because we don't know exactly how big an integral type is, nor exactly how much room we need to store the size. The size_t type exists as a type that is guaranteed to be the right size for your system.

like image 21
Chris Lutz Avatar answered Nov 12 '22 18:11

Chris Lutz