Andromeda
Andromeda

Reputation: 49

How can I get a string from user without spaces using scanf?

This is a C code to get a string for types of brackets '()' & '<>' & '{}' & '[]' from user. The length of this string is n and it is an user input.

int main()
{
  long int n;
  int i;
  scanf("%lld", &n);
  char array[n];
  for(i=0; i<n ; i++)
  {
     scanf("%s", &array[i]);
  }
 }

The problem is I want to get the string without any spaces between them from user. But, this code is working for the input with space between each character and give the correct result.

For example, if I type {(() the program won't run. but if I type { ( ( ) the program shows the correct result. How can I solve this problem?

Upvotes: 1

Views: 4281

Answers (2)

gsamaras
gsamaras

Reputation: 73384

Change:

scanf("%s", &array[i]);

to this:

scanf(" %c", &array[i]);

since what you attempt to do is read your string character by character.

Please notice the space before %c, which will consume the trailing newline that is going to be left in the stdin buffer from when you entered n.

I had wrote about the caution when reading a character with scanf() here.

Now, even if you use {(() or { ( ( ) for the input, it will be the same, since scanf() will ignore the whitespaces.

However, you should null terminate your string, if you want it to be used by standard functions, which you almost certainly want. For example, if you were to use printf("%s", array);, then you must have array null terminated.

An approach to this, assuming that the user will input correctly (in a perfect world), you could do that:

#include <stdio.h>
int main()
{
  long int n;
  int i;
  scanf("%ld", &n);

  // create an extra cell to store the null terminating character
  char array[n + 1];

  // read the 'n' characters of the user
  for(i=0; i<n ; i++)
  {
     scanf(" %c", &array[i]);
  }

  // null terminate the string
  array[n] = '\0';

  // now all standard functions can be used by your string
  printf("%s\n", array);

  return 0;
 }

PS: scanf("%lld", &n); --> scanf("%ld", &n);. Use your compiler's warnings! It will tell you about it..

Upvotes: 3

Lo&#239;c France
Lo&#239;c France

Reputation: 324

If you want to make sure the user types at least 1 space character between each 'valid' character, you can just wait in the loop until the user adds a space character.


    char c;
    for (i = 0; i < n; i++)
    {
        c = '\0';
        while (c != ' ')        // wait for the user to type a space character
        {
            scanf ("%s", &c);
        }
        while (c == ' ')        // wait for the user to type something else
        {
            scanf ("%s", &c);
        }
        array[i] = c;
    }

Upvotes: 0

Related Questions