How to Take whitespace in Input in C

2019-04-06 18:29发布

I wanted to take character array from console and it also include white spaces, the only method i know in C is scanf, but it miss stop taking input once it hit with white space. What i should do?

Here is what i am doing.

char address[100];

scanf("%s", address);

7条回答
贼婆χ
2楼-- · 2019-04-06 18:47

See fgets()

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.

char *fgets(char *s, int size, FILE *stream);

Further detail available in many SO questions, for example input-string-through-scanf.

(Due to popular demand, refrence to gets() was removed)

查看更多
迷人小祖宗
3楼-- · 2019-04-06 18:49

Personally I would use fgets, but that has been already pointed out here. One way of doiung it using scanf would be

scanf("%[^\n]", address);

This takes in all chars until a '\n' is found.

查看更多
倾城 Initia
4楼-- · 2019-04-06 18:50

You can try something like this:

char str[100];
scanf("%99[0-9a-zA-Z ]s", str);
printf("%s\n", str);
查看更多
5楼-- · 2019-04-06 18:53

There are ways to do it with scanf(), but in my humble opinion they get ugly fast. The common pattern (that surprisingly hasn't been mentioned yet) is to read the string in with fgets() and then use sscanf() to process it. sscanf() works like scanf(), only instead of processing the standard input stream, it processes a string that you pass to it (the same way printf() and sprintf() are related). The basics:

char s[100], str[100];
int i, x;
fgets(s, 100, stdin);
if(sscanf(s, "%d %x %s", &i, &x, str) != 3)
  {
    // our three variables weren't all set - probably an invalid string
    // either handle the error or set default values here.
  }
查看更多
相关推荐>>
6楼-- · 2019-04-06 19:01

If you want to take input until new line using a dynamic array inside struct, this may be useful:

#include<stdio.h>
#include<stdlib.h>

struct student{
char *name;
};

int main()
{
        struct student s;

        s.name = malloc(sizeof(char *));

        printf("Name: ");
        // fgets(s.name, 10, stdin); // this would limit your input to 10 characters.

        scanf("%[^\n]", s.name);   

        printf("You Entered: \n\n");

        printf("%s\n", s.name);
}
查看更多
劳资没心,怎么记你
7楼-- · 2019-04-06 19:01

My style.

 #include <stdio.h>

    #define charIsimUzunlugu 30

        struct personelTanim
        {       
            char adSoyad[charIsimUzunlugu];             
        } personel;

    printf(" your char       : ");
    scanf("%[^\n]",personel.adSoyad);

    printf("\n\n%s",personel.adSoyad);
查看更多
登录 后发表回答