使用fgets()。 它将从您选择的流中读取一条完整的行(Stdin,我想您正在寻找)。 您案件的一个例子:
char address[100];
fgets(address, 100, stdin);
fgets()最多会读取第二个参数(减一个)中传递的字符数。 没有缓冲区溢出,您将获得整个阵容,包括一个newline字符(或最多eof)。 请注意,由于要读取的最大字符数是参数之一,因此您可能会得到部分行。 检查返回字符串中的最后一个字符是否为' ',您会知道您有一条完整的线路。 EOF检测也很简单。
errno
您可以尝试这样的事情:
char str[100];
scanf("%99[0-9a-zA-Z ]s", str);
printf("%s\n", str);
有这样做
scanf()
fgets()
,但以我的拙见,它们变得丑陋。常见的模式(尚未提到这一点)是用
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'
'已找到
见
fgets()
char *fgets(char *s, int size, FILE *stream);
further细节可在许多SO问题中提供,例如
输入 - 弦乐 - 简单 - canf(由于受欢迎的需求,将其转化为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);