aDabOfRanch
aDabOfRanch

Reputation: 147

How to retrieve a portion of a string?

I'm reading in a string of file permissions from stdin and I want to create another string that will hold all characters expect the first from the string the user inputs in stdin.

int main(){
  char allPermissions[10];
  char permissions[9];

  scanf("%s", allPermissions);


  for(int i = 1; i <= 9; i++) {
    char temp = allPermissions[i];
    //printf("%c", temp);
    permissions[i-1] = temp;
  }
  printf("%s\n", permissions);

  return 0;
}

If the user inputs: drwx------

Then I expect the program to output: rwx------

But what I get is: rwx------drwx-------

And I'm not entirely sure why.

Upvotes: 1

Views: 136

Answers (2)

Govind Parmar
Govind Parmar

Reputation: 21542

Looping through the entire string and copying each element one by one into the destination string works, but it is inefficient and unidiomatic C. You can accomplish this in O(1); after reading the string from stdin, just point one after the start of the string:

printf("%s\n", allPermissions + 1);

This will also work for operations such as copying the string to a new buffer:

strcpy(permissions, allPermissions + 1);

Do note that an array size of 10 is insufficient for reading a string like 'drwx------' since you also need to take the null terminator into account. In general, I wouldn't use scanf-family functions to read from stdin; fgets is a better choice.

Upvotes: 2

Arash Milani
Arash Milani

Reputation: 6308

You should add null-terminator character to the end of your character strings. So although drwx------ is 10 characters to you, it will take 11 chars (including the \0) to store it in the memory.

int main(){
  char allPermissions[11];
  char permissions[10];

  scanf("%s", allPermissions);

  for(int i = 1; i <= 10; i++) {
    char temp = allPermissions[i];
    //printf("%c", temp);
    permissions[i-1] = temp;
  }
  printf("%s\n", permissions);

  return 0;
}

Upvotes: 1

Related Questions