-1

I want to get string elements with space. Let's say I have a string called test and user will enter something in every cell, for instance he will enter colors he will enter the colors in a single line like; Green Yellow Blue Black - then he will press enter then program take everything until the space entered and put it on the first element of string then continues. In this case the string should be according to;

test[0] "Green"
test[1] "Yellow"
test[2] "Blue"
test[3] "Black"

I have tried to write it with 2 nested loops but I couldn't manage to get strings with space

long i
char* test[4]


printf("Enter your guess:\n");
for(i=0;i<5;i++)
{
    while(test[i]!=" ")
    {
        scanf("%s", test[i]);
    }



}
  • Also see: [How do I properly compare strings in C?](http://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c) – P.P Aug 10 '16 at 11:16
  • This question is not duplicate, the link you put mentions completely different thing. – C. Johnson Aug 10 '16 at 11:27

1 Answers1

1

That's because scanf (and family) with the "%s" format only reads space delimited words. To get a whole line you should use fgets instead.

Do note that fgets puts the ending newline in the buffer you provide (if it can fit)


Also, you definitely need to allocate memory for the strings first. The code you show seems to tell us that you don't initialize the array test which means you either have an array of null pointers (if test is a global variable) or have pointers being indeterminate (if test is a local variable. Both of these will lead to undefined behavior.

Depending on platform, you might have a function available called getline which allows you to read lines, and also allocates memory for you. As with fgets the ending newline will be added to the buffer.


Lastly, you can't compare string using the == operator, it will only compare the pointers and not what they point to. Therefore comparing using == will almost always be false, unless both pointers point to the same memory.

To compare string you should use the strcmp function.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550
  • thank you for your reply, is it possible to get input of a single line and put it to each cell, with an easier way ? – C. Johnson Aug 10 '16 at 11:28
  • @C.Johnson The only way to get multiple lines of input, each line written into its own string, is with a loop. So no there's really no other way to do it. – Some programmer dude Aug 10 '16 at 11:35