How to use scanf () to read a string with spaces in C language?

Source: Internet
Author: User

Landlord

Comment posted: 2011-01-14 15:39:55

#include <stdio.h>

int main (void)
{
int i;
Char a[5];

scanf ("%s", a);
printf ("%s\n", a);

return 0;

}

Run input Hello World
Enter
Then the output is only the part before the space, how to put the space after the part also output it?

2 floor

Reply at: 2011-01-14 17:27:23

Who says scanf can't do it?

#include <stdio.h>
int main ()
{
Char str[128];
scanf ("%[^\n]", str);
printf ("%s\n", str);
return 0;
}

Regular Expressions in scanf


int i;
//scanf ("%d%[abc]%s", &i, str, str2);
//printf ("%d%s%s\n", I,STR,STR2);
//scanf ("%[a-za-z0-9]", str);
//scanf ("%[^ABCE]", str);
scanf ("%[^a-z]", str);
printf ("%s\n", str);

2. Read in an address and display the contents of the memory address
int main (void)
{
Char ch= ' C ';
printf ("%p\n", &ch); Print the address of Ch.
Char *p;
cout<< "Enter an address:";
scanf ("%p", &p); Input the address displayed above
printf ("Value at location%p is%c\n", p,*p);
return 0;
}

3. Discard unwanted whitespace characters: scanf ("%c%c");

4. A non-whitespace character in the control string: Causes scanf () to read in and discard a matching character in the input stream. "%d,%d";

5. Compression Input: Add * to the format code before the user can tell scanf () to read the field, but not assign it to any variables.
scanf ("%c%*c, &ch); Use this method to eat the extra carriage return while the character is being processed.


Example 1: Extracting Tom from <sip:[email protected]>
Const char* URL = "<sip:[email protected]>";
Char uri[10] = {0};
sscanf (URL, "%*[^:]:%[^@]", URI);
cout << URIs << Endl;

Example 2: Extracting 12DDWDFF from Iios/[email protected]
Const char* s = "iios/[email protected]";
Char buf[20];
SSCANF (S, "%*[^/]/%[^@]", buf);
cout << buf << Endl;

3 floor

Reply at: 2011-01-14 21:15:47

int t[999];
int sum=0;
while (scanf ("%c", &t[sum++])!=eof);

How to use scanf () to read a string with spaces in C language?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.