0

I was wondering how you would assign multiple variables from a single line of user input if it contained symbols. Such as, if the user input was 5-25-1995, is it possible to assign 5, 25, and 1995 to different variables and ignore the "-"'s? I have been trying to use cin.ignore(), but haven't had any luck as of yet.

Thanks.

Short version:

user inputs "3-24-1995"

desired outcome

int month is 3, int day is 24, int year is 25,

user2057847
  • 47
  • 1
  • 1
  • 8
  • 1
    Nominate to reopen. "Splitting a string" implies one possible answer (read into a single string, then split) whereas the accepted answer is in fact a better approximation of what's asked. I.e. This question is both wider (has more possible answers) and narrower (assumes a specific string source) than the linked "duplicate" – MSalters Mar 11 '13 at 12:07
  • Good Newtons, the "duplicate" is only vaguely similar to this question. Most of the answers there either don't answer this question, many are unnecessarily complicated, and a few just plain suck. (For a less rage-filled argument for reopening, see @MSalters comment above.) Just because you have a hammer (read: a lot of rep) doesn't mean that everything long and skinny is a nail (read: not every question vaguely on the same topic is a duplicate); please wield your hammers more wisely. – Nicu Stiurca Mar 11 '13 at 20:34
  • I got banned for this? – user2057847 Mar 12 '13 at 20:31

2 Answers2

4
char dummy;
int month, day, year;
cin >> month >> dummy >> day >> dummy >> year;
Nicu Stiurca
  • 8,747
  • 8
  • 40
  • 48
0

As your specific requirement was that the input be in the form "3-24-1995", therefore may be something along the lines will comply with your needs and produce what you wanted.

/* Code */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main ()
{
  char str[] ="3-24-1995"; // Your input that you will have some way of getting
  char * month, *day, *year;

  month=strtok (str,"-");

  day = strtok (NULL,"-");
  year = strtok (NULL,"-");

  // Here, converting to int, just because you were looking to convert it into 
  // int otherwise you could just leave it un converted too.

  printf("month: %d day: %d year: %d\n",atoi(month), atoi(day), atoi(year));
}
triangorithm
  • 111
  • 9