-2

I'm trying to take user input using the getline() function. I store the input and point to it with a char *pointer. Now I want to split the string at the white space, if there is any, but I can't change a string literal. So my idea was to transfer a copy of the input to a char array so I could then play around with it. The only issue is I don't know the size of the users input yet so I can't specify the size of the array I want.

Any ideas how I can get around this, I'm probably missing something, I'm new to C from a Java background.

Many Thanks!

Ryan H
  • 85
  • 4
  • 13
  • Maybe,proper usage of `malloc`! – Am_I_Helpful Nov 09 '14 at 17:55
  • Where do you get the `char*` that you use to store the initial user input? – Wyzard Nov 09 '14 at 17:58
  • Instead of copying the string (which does not bring you any closer to the solution), use an array of `(From, To)` index pairs delimiting the words. You will have to allocate for at least `strlen(input)/2` such pairs. Another option is to process the words on the fly, without keeping a trace. –  Nov 09 '14 at 18:04
  • 5
    @James Loper A user can not enter a string literal.:) A string literal is a part of the source code of your program. – Vlad from Moscow Nov 09 '14 at 18:09
  • Many thanks... I was obviously confused with the difference between constant char arrays and non-const... thanks again @VladfromMoscow – Ryan H Nov 09 '14 at 18:16

2 Answers2

1

You read the line, figure out its size, then make a copy of that size.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

If you store a user input with some function getline (there is no such a function in C Standard) then you can split it into tokens by using standard C function strtok declared in header <string.h> If you do not want to change the original string then you can write the required function yourself by means of searching blank and non-blank characters in the string.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • "Some function `getline`", considering the wording of the question, I think it's fair to assume it is not just some function with that name, but the common, standard (POSIX.1-2008) `getline`, even if question isn't tagged with posix tag. – hyde Nov 09 '14 at 18:29
  • @hyde Maybe but in any case it either allocates memory itself or uses user supplied argument to store the ibput. – Vlad from Moscow Nov 09 '14 at 18:30