Tyler
Tyler

Reputation: 11

read two strings into 1 variable

So I am working on an assignment where we will be reading in a first name followed by a last name and other information from an input file. The teacher wants us to make thie first and last name one variable.

For Example:

Input: (Faculty#, first name, last name, age) "123 Suzie Cue 42"

How would I store "suzie cue" in one variable while still storing the other integers in their own variables? In other words, I have 4 inputs from the file, but I have only 3 variables.

EDIT-------I had to reword the question, because I realized I didn't give enough information. Sorry about the confusion.

Upvotes: 1

Views: 221

Answers (4)

David C. Rankin
David C. Rankin

Reputation: 84531

When reading any input that is entered as a line of text it is generally better to use line-oriented input to read the entire line into a string (or buffer). This allows you the ability to parse that buffer using any method you like. This is far more flexible than attempting to shoehorn the line format into a scanf statement.

Your primary tools for line-oriented input are fgets and getline. Either is fine, but I prefer getline as it provides the actual number of characters read as a return and has the ability to dynamically allocate the buffer for you sufficient to hold the entire string read. (you have to remember to free the space when you are done with it)

Parsing the buffer is fairly simple. You have values separated by spaces. You know the first space comes after the Faculty# and you know the last space separates the name from the age. You can find the first and last space very trivially with strchr and strrchr. You know everything in between is the name. This has a huge benefit. It doesn't matter is the name is a first last, first middle last, first middle last, suffix, etc... You get it as name.

After you have successfully parsed the buffer, you have Facuty# and age as stings. If you need them as integers or longs, that is no problem at all. Simple conversion using atoi or strtol makes conversion a snap. This is why line-oriented input is preferred. You have total control over parsing the buffer and you are not limited by the scanf format string.

Here is an example of getting the data using line oriented input. You can store all values permanently in an array if you like. I have just printed them for the purpose of this question. Look the example over and let me know if you have questions:

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

output:

$ ./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

Upvotes: 1

Gopi
Gopi

Reputation: 19864

You can use fgets()

char c[50];
fgets(c,sizeof(c),stdin);

Upvotes: 0

Rush
Rush

Reputation: 496

Try the below

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

Upvotes: 0

Anbu.Sankar
Anbu.Sankar

Reputation: 1346

I think,may be , your teacher intention is to teach for scanning string with space successfully. So use

fgets or

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

scanf ("%25s",name);.

Upvotes: 0

Related Questions