8

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
shobhnit
  • 141
  • 1
  • 2
  • 9
  • 7
    In real life you would simply use `fgets`. – Matteo Italia Feb 20 '11 at 00:57
  • 3
    In real life you would also use google. [Exact duplicate of this](http://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf) – Reno Feb 20 '11 at 02:18

4 Answers4

16

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

Splat
  • 753
  • 3
  • 10
  • 1
    `"%80[^\n]"` should be sufficient, since a `FILE *` opened in text mode (like `stdin`) will convert Windows/whatever newlines to the `\n` character. – Chris Lutz Feb 20 '11 at 02:08
3

@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.

Community
  • 1
  • 1
Chris Lutz
  • 73,191
  • 16
  • 130
  • 183
0
#include "stdio.h"
#include "conio.h"

void main()
{
char str[20];
int i;
clrscr();
printf("Enter your string");
scanf("%[^\t\n]s",str); --scanf to accept multi-word string
i = strlen(str); -- variable i to store length of entered string
printf("%s %d",str,i); -- display the entered string and length of string
getch();

}

output :

enter your string : My name is james
display output : My name is james 16
Vishwanath Dalvi
  • 35,388
  • 41
  • 123
  • 155
-1
#include "stdio.h"
int main()
{
    char str[20];
    int i,t;
    scanf("%d",&t); 
    while(t--){
        fflush(stdin);
        scanf(" %[^\t\n]s",str);// --scanf to accept multi-word string
        i = strlen(str);// -- variable i to store length of entered string
        printf("%s %d\n",str,i);// -- display the entered string and length of string
    }

    return 0;
}
dashtinejad
  • 6,193
  • 4
  • 28
  • 44