简体   繁体   中英

Reading a string from stdin in c

I wrote a simple program to read a string.

void main()
{
    char *str; /*didn't allocate memory*/
    scanf(" %s",str);
    printf("%s",str);
}

But it is causing a segmentation fault. Whereas the next one isn't.

void main()
{
    char *str;
    scanf(" %c",str);
    printf("%c\n",str);
}

Would someone mind to clarify how actually this works?

You string isn't allocated. which mean you are writing somewhere you didn't ask for.

however what you can do is:

#include <stdio.h>    
#include <stdlib.h>

int main(int argc, char *argv[])

{
  char c;
  while (scanf("%c",&c) && c != '\n')
    printf("%c",c);
  printf("\n");

  return 0;
}

It will read every characters you send in input until you press return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM