-1

I need to fill an array with a string that is input by a user. For example user enters such string like these: "St/80" We know the length before user enters it btw. I wanna do this:

    array[0]='S';
    array[1]='t';
    array[2]='/';
    array[3]=8;
    array[4]=0;
Aldrich
  • 3
  • 6
  • There is a magic command called `scanf();`. Look into it. :) – Haris Mar 07 '16 at 17:03
  • @Haris `scanf()` is rarely the correct answer to inputting a string in C. `fgets()` or `getline()` would be better choices. – Kurt Stutsman Mar 07 '16 at 17:11
  • @KurtStutsman, True. But for a beginner, and for the input he provided. I thought `scanf()` would be the most apt. But ya, `fgets()` is a better option. – Haris Mar 07 '16 at 17:13

1 Answers1

1

Look at the code below:

#include <stdio.h>
int main(void)
{
    char arr[10];
    scanf("%9s", arr);
    printf("%s",arr);
    return 0;
}

here if your input string is "St/80" then it will assign as below:

array[0]='S';
array[1]='t';
array[2]='/';
array[3]=8;
array[4]=0;

also you can increase the size of string by increasing the index of arr.

cjahangir
  • 1,773
  • 18
  • 27
  • 1
    Using `scanf()` like this is a buffer exploit waiting to happen. – Kurt Stutsman Mar 07 '16 at 17:12
  • thats right @KurtStutsman, but here it can be a solution of this problem. – cjahangir Mar 07 '16 at 17:14
  • 2
    If you're going to use `scanf()` at least show them to use the `%9s` form so we're teaching beginners to code safely from the beginning. Otherwise they tend to develop long-lived poor coding practices. – Kurt Stutsman Mar 07 '16 at 17:15
  • thank you so much it works but I don't get "%9s" part. What "%9s" stands for? why don't we use %s instead of %9s i mean. – Aldrich Mar 07 '16 at 17:45
  • 2
    ok. %9s means it will take a string input which contains less than or equal to 9 characters. you can change this number. – cjahangir Mar 07 '16 at 17:48