C 将两个字符串读入一个变量

C 将两个字符串读入一个变量,c,string,scanf,C,String,Scanf,所以我正在做一项作业,我们将从输入文件中读取一个名字,后跟一个姓氏和其他信息。老师要我们把名字和姓氏作为一个变量 例如: 输入: (教员、名字、姓氏、年龄) “123苏西球杆42” 如何将“suzie cue”存储在一个变量中,同时将其他整数存储在它们自己的变量中? 换句话说,我从文件中有4个输入,但我只有3个变量 编辑------我不得不改写这个问题,因为我意识到我没有提供足够的信息。很抱歉造成混淆。您可以使用fgets() 我想,可能是,你们老师的用意是教你们用空格扫描字符串。所以使用 fg

所以我正在做一项作业,我们将从输入文件中读取一个名字,后跟一个姓氏和其他信息。老师要我们把名字和姓氏作为一个变量

例如:

输入: (教员、名字、姓氏、年龄) “123苏西球杆42”

如何将“suzie cue”存储在一个变量中,同时将其他整数存储在它们自己的变量中? 换句话说,我从文件中有4个输入,但我只有3个变量

编辑------我不得不改写这个问题,因为我意识到我没有提供足够的信息。很抱歉造成混淆。

您可以使用
fgets()


我想,可能是,你们老师的用意是教你们用空格扫描字符串。所以使用

fgets

scanf(“%[^\n]”,名称)

scanf(“%25s”,名称)

请尝试以下方法

#include <stdio.h>
#include <string.h>

int main ()
{
  char name[80];
  char str[40];

  printf ("Enter your first name: ");
  scanf ("%s", str);
  int flen = strlen(str);
  strncat(name, str, flen);
  strncat(name, " ", 1);

  printf ("Enter your last name: ");
  scanf (" %s", str);
  flen = strlen(str);
  strncat(name, str, flen);
  printf("Name is :%s\n",name);

  return 0;
}
#包括
#包括
int main()
{
字符名[80];
char-str[40];
printf(“输入您的名字:”);
scanf(“%s”,str);
int-flen=strlen(str);
strncat(姓名、str、flen);
strncat(名称,“,1);
printf(“输入您的姓氏:”);
scanf(“%s”,str);
flen=strlen(str);
strncat(姓名、str、flen);
printf(“名称为:%s\n”,名称);
返回0;
}

当读取作为文本行输入的任何输入时通常最好使用面向行的输入将整行读入字符串(或缓冲区)。这使您能够使用任何喜欢的方法解析该缓冲区。这比试图将行格式硬塞进
scanf
语句要灵活得多

面向行输入的主要工具是
fgets
getline
。两者都可以,但我更喜欢
getline
,因为它提供了作为返回读取的实际字符数,并且能够为您动态分配足够容纳整个字符串读取的缓冲区。(使用完后,请记住释放空间)

解析缓冲区相当简单。您的值由
空格分隔。你知道第一个空格在
教员之后,你知道最后一个空格将
姓名
年龄
分开。使用
strchr
strrchr
可以很容易地找到第一个和最后一个空格。你知道中间的一切都是名字。这有巨大的好处。不要紧的是名称是
首末
首中末
首中末,后缀
,等等。。。你得到它的名字

成功解析缓冲区后,将
Facuty#
age
作为stings。如果您需要将它们作为
整数
长数
,那根本没有问题。使用
atoi
strtol
进行简单的转换,即可快速完成转换。这就是为什么首选面向行的输入。您可以完全控制对缓冲区的解析,并且不受
scanf格式字符串的限制

下面是一个使用面向行的输入获取数据的示例。如果愿意,可以将所有值永久存储在数组中。我只是为了这个问题而把它们印出来的。查看示例,如果您有问题,请告诉我:

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

int main (void) {

    char *line = NULL;      /* pointer to use with getline ()       */
    ssize_t read = 0;       /* number of chars actually read        */
    size_t n = 0;           /* limit read to n chars (0 - no limit) */
    int cnt = 0;            /* count of lines read                  */
    int spcs;               /* counter to count spaces in line      */
    char *p = NULL;         /* general pointer to use               */

    char *fnumber = NULL;   /* faculty number   */
    char *name = NULL;      /* teacher name     */
    char *age = NULL;       /* teacher age      */

    printf ("\n Enter Faculty Information (Faculty# Name Age) (press [ctrl+d] when done)\n\n");

    while (printf ("  input: ") && (read = getline (&line, &n, stdin)) != -1) {

        if (read > 0 && *line != '\n') {    /* validate input, not just [enter] */

            if (line[read - 1] == '\n') {   /* strip newline */
                line[read - 1] = 0;
                read--;
            }

            p = line;                   /* validate at least 3 spaces in line   */
            spcs = 0;
            while (*p) {
                if (*p == ' ')
                    spcs++;
                    p++;
            }

            if (spcs < 3)               /* if not 3 spaces, get new input       */
                continue;

            p = strrchr (line, ' ');    /* find the last space in line          */

            age = strdup (++p);         /* increment pointer and read age       */
            --p;                        /* decrement pointer and set null       */
            *p = 0;                     /* line now ends after name             */

            p = strchr (line, ' ');     /* find first space in line             */
            *p++ = 0;                   /* set to null, then increment pointer  */

            fnumber = strdup (line);    /* read faculty number (now line)       */
            name = strdup (p);          /* read name (now p)                    */

            printf ("\n    Faculty #: %-10s name: %-24s age: %s\n\n", fnumber, name, age);

            /* free all memory allocated by strdup*/
            if (fnumber) free (fnumber);
            if (name) free (name);
            if (age) free (age);

            cnt++;                      /* count this as a valid read           */
        }
    }

    if (line) free (line);              /* free line allocated by getline       */

    printf ("\n\n  Number of faculty entered : %d\n\n", cnt);

    return 0;
}

scanf(“%s”,name)
scanf()
fgets()
另外,请阅读有关数组以及
name[25][2]
(2d array)的含义。bt,数组应该类似于
char name[2][25];并使用
scanf(“%s”,name[0])`
fgets(name,sizeof name,stdin)
@GrijeshChauhan不需要这样做。
c
是我的编译器知道如何处理的默认值,还是一个未声明的新变量?@Tyler:我已经修复了代码中的小错误,这应该使Gopi的意图更加明显。如果我从文件中读取,并且每行都有其他信息,该怎么办?例如:学生证、生日、名字、姓氏和年龄?这会改变事情吗?对于这一点,你可能会在你的问题中给出适当的信息。谢谢,这真的帮助我更了解它!我很高兴这有帮助。C语言是一种非常精确的语言,它要求读者愿意阅读整本书,而不是浏览页面。(知道每个命令的每个部分都做了些什么,如果你只知道部分发生了什么,红色信号就会出现,查找并验证)也就是说,C通常提供许多不同的方法来完成任何一项任务。当你把头撞到墙上足够长的时间后,你开始寻找更简单的做事方法。坚持下去,不要走捷径,你会做得很好的。祝你好运(如果有帮助,您可以通过数字选择答案)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void) {

    char *line = NULL;      /* pointer to use with getline ()       */
    ssize_t read = 0;       /* number of chars actually read        */
    size_t n = 0;           /* limit read to n chars (0 - no limit) */
    int cnt = 0;            /* count of lines read                  */
    int spcs;               /* counter to count spaces in line      */
    char *p = NULL;         /* general pointer to use               */

    char *fnumber = NULL;   /* faculty number   */
    char *name = NULL;      /* teacher name     */
    char *age = NULL;       /* teacher age      */

    printf ("\n Enter Faculty Information (Faculty# Name Age) (press [ctrl+d] when done)\n\n");

    while (printf ("  input: ") && (read = getline (&line, &n, stdin)) != -1) {

        if (read > 0 && *line != '\n') {    /* validate input, not just [enter] */

            if (line[read - 1] == '\n') {   /* strip newline */
                line[read - 1] = 0;
                read--;
            }

            p = line;                   /* validate at least 3 spaces in line   */
            spcs = 0;
            while (*p) {
                if (*p == ' ')
                    spcs++;
                    p++;
            }

            if (spcs < 3)               /* if not 3 spaces, get new input       */
                continue;

            p = strrchr (line, ' ');    /* find the last space in line          */

            age = strdup (++p);         /* increment pointer and read age       */
            --p;                        /* decrement pointer and set null       */
            *p = 0;                     /* line now ends after name             */

            p = strchr (line, ' ');     /* find first space in line             */
            *p++ = 0;                   /* set to null, then increment pointer  */

            fnumber = strdup (line);    /* read faculty number (now line)       */
            name = strdup (p);          /* read name (now p)                    */

            printf ("\n    Faculty #: %-10s name: %-24s age: %s\n\n", fnumber, name, age);

            /* free all memory allocated by strdup*/
            if (fnumber) free (fnumber);
            if (name) free (name);
            if (age) free (age);

            cnt++;                      /* count this as a valid read           */
        }
    }

    if (line) free (line);              /* free line allocated by getline       */

    printf ("\n\n  Number of faculty entered : %d\n\n", cnt);

    return 0;
}
$ ./bin/faculty

 Enter Faculty Information (Faculty# Name Age) (press [ctrl+d] when done)

  input: 100 Mary P. Teacher 45

    Faculty #: 100        name: Mary P. Teacher          age: 45

  input: 101 John J. Butterworth, Jr. 52

    Faculty #: 101        name: John J. Butterworth, Jr. age: 52

  input: 102 Henry F. Principal 62

    Faculty #: 102        name: Henry F. Principal       age: 62

  input: 103 Jim L. Lee, III, PhD 71

    Faculty #: 103        name: Jim L. Lee, III, PhD     age: 71

  input:

  Number of faculty entered : 4