如何在C

问题描述 投票:0回答:5

使用fgets()。 它将从您选择的流中读取一条完整的行(Stdin,我想您正在寻找)。 您案件的一个例子:

char address[100]; fgets(address, 100, stdin);
fgets()最多会读取第二个参数(减一个)中传递的字符数。  没有缓冲区溢出,您将获得整个阵容,包括一个newline字符(或最多eof)。  请注意,由于要读取的最大字符数是参数之一,因此您可能会得到部分行。  检查返回字符串中的最后一个字符是否为'
',您会知道您有一条完整的线路。  EOF检测也很简单。 
c whitespace scanf
5个回答
14
投票
返回值和向

errno

的支票应为您提供帮助。 thanks to Chris(下图),关于部分线的观点。
    

您可以尝试这样的事情:

char str[100];
scanf("%99[0-9a-zA-Z ]s", str);
printf("%s\n", str);
    

有这样做

scanf()

7
投票

fgets()

,但以我的拙见,它们变得丑陋。常见的模式(尚未提到这一点)是用

1
投票

读取字符串,然后使用

sscanf()
对其进行处理。 scanf()
工作类似于
printf()
,而不是处理标准输入流,而是处理您传递给它的字符串(以相同的方式sprintf()
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. }
是相关的)。基础知识:
scanf("%[^\n]", address);
    
我会使用fgets,但这已经在这里指出。使用scanf做到这一点的一种方法是
fgets()
this摄取所有魅力,直到A' '已找到


1
投票

fgets()

读取最多比流的大小字符少,然后将它们存储到s指向的缓冲区中。阅读在EOF或NEWLINE之后停止。如果读取新线,则将其存储在缓冲区中。 a''是在缓冲区中的最后一个角色之后存储的。
char *fgets(char *s, int size, FILE *stream);

further细节可在许多SO问题中提供,例如

输入 - 弦乐 - 简单 - canf

0
投票

(由于受欢迎的需求,将其转化为gets()

如果您想使用Dynamic Array进行结构内的动态数组进行输入,这可能很有用:

#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);
}

我的风格
 #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);

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.