-4

I can't pass strings that contain an apostrophe as a command-line argument.

Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned int ascii_values (const char *word);
int main (int argc, char *argv[])
{
    if (argc < 2)
    {
        printf("Usage: ./ascii WORD\n");
    }
    for (int i = 1; i < argc; i++)
    {
        int ascii = ascii_values(argv[i]);
        printf("The ascii value is %i\n", ascii);
    }
}

unsigned int ascii_values (const char *word)
{
    int l = strlen(word);
    int ascii = 0;
    for(int i = 0; i < l; i++)
    {
        ascii = word[i];
    }
    return ascii;
}

If I input the command-line arguments into the terminal:

./ascii ' 

The following happens and gets stuck there:

>

Instead of:

The ascii value is 39.

Any idea of why it's doing that?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 8
    `./ascii \'` or `./ascii "'"` – bolov Feb 10 '23 at 13:55
  • 2
    This is an issue with how you are using the shell, not your C code. `'` has special meaning to the shell, so you need to escape it to pass a *literal* single quote as an argument. – chepner Feb 10 '23 at 14:04
  • 3
    The `>` is the secondary prompt; the shell is waiting for more input to complete the quoted word you just started to input. – chepner Feb 10 '23 at 14:05
  • @Charles Duffy, This isn't a dupe of [that Q&A](https://stackoverflow.com/questions/5720194/how-do-i-pass-on-script-arguments-that-contain-quotes-spaces). Not only is the question different, but none of the answers apply here. I looked for while, and couldn't find anything about quoting single-quotes. (The closest was quoting single-quotes inside of a single-quoted literal.) – ikegami Feb 10 '23 at 15:59
  • @Alex Sugimoto Try invoking a command like `cat '` or `grep '` or even `date '`. Then when you get that `>` prompt, try typing another `'`. (And if you do that with your program, you'll end up with the ASCII value for a newline character!) – Steve Summit Feb 10 '23 at 16:14

1 Answers1

2

Single quote is a special shell character so you have to escape it. Either enter it as \'or "'".

Allan Wind
  • 23,068
  • 5
  • 28
  • 38