-1

This is my code so far:

#include <stdio.h>
#define DIM 100
int main (){

    char rest[DIM];
    scanf ("%s", rest);
    char first;
    first = rest[0];

The input the user will put will either be something like "1 dsdsff e" or "2 dej deer". How can I save the different words in rest that will be separated by " "? And disregard the first number since I've already stored it.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Aen
  • 1

2 Answers2

1

You can use scanf with formatted template

int n;
char rest1[DIM], rest2[DIM];

scanf("%d %s %s", &n, rest1, rest2);

In that case input '42 text1 text2' will gave n == 42, rest1 will contain 'text1' and rest2 will contain 'text2'

LibertyPaul
  • 1,139
  • 8
  • 26
  • the thing is that rest1 will be " text1" and I do not want the space at the begining – Aen Mar 27 '16 at 18:28
  • 1
    @Aen: `%s` reads a whitespace delimited string, so no spaces will ever be stored in `rest1` or `rest2`. Note that the space before `%s` is irrelevant -- spaces will be skipped regardless. – Chris Dodd Mar 27 '16 at 18:32
  • @ChrisDodd yeah, you're right. I was doing something wrong. Anyway, this is a good solution except that sometimes the input is simply "1" (which I forgot to mention) – Aen Mar 27 '16 at 18:35
  • @Aen In case when you dont know actual number of parameters you should read whole string and parse them one-by-one – LibertyPaul Mar 27 '16 at 18:59
  • @LibertyPaul how? I've tried strtok but since I want to save them it's not working right – Aen Mar 27 '16 at 19:12
-1

You are storing the string in an array that's correct, then you have to split that array by delimiter ' '. Here is the code that might help you.

Split string with delimiters in C

Community
  • 1
  • 1
viveksinghggits
  • 661
  • 14
  • 35