c reading and writing strings visual studio 2013

276 views Asked by At

Every time I run this it stops working when I enter the string.I use visual studio 2013.Here's my code:

   #include<stdio.h>
   #include<stdlib.h>
   int main(void){
    char x[10];
    scanf("%s",x);
    printf("%s",x);
    system("pause");
    return 0;
}
3

There are 3 answers

2
Some programmer dude On

What probably happens is that the stdout output buffer is not flushed. By default stdout is line buffered meaning the output written to stdout will not actually be output until there is a newline.

So the solution is simply to write a newline:

printf("%s\n",x);

Also note that you can't write input more than nine characters, or you will write beyond the bounds of the array x and have undefined behavior. The number nine comes from your array being ten char big, and strings in C needs an extra character to terminate the string, so the largest string you can put in x is ten minus one.

3
user3476093 On

Try this:

#include<stdio.h>
#include<stdlib.h>
int main(void)
{
    char *buffer = calloc(1024, sizeof(char)); // you could replace sizeof(char) with 1 if you wanted
    scanf("%s", buffer);
    unsigned lng = strlen(buffer);
    buffer = realloc(buffer, (lng + 1)); // note sizeof(char) == 1, so no need to add it
    printf("%s\n", buffer);
    system("pause");
    free(buffer);
    return (0);
}
0
AudioBubble On

If you put more than 9 characters into x then your program will give undefined behavior. Suppose, you input abcdefghi, then actual content of x is follows:

x[0] = 'a'
x[1] = 'b'
x[2] = 'c'
x[3] = 'd'
x[4] = 'e'
x[5] = 'f'
x[6] = 'g'
x[7] = 'h'
x[8] = 'i'
x[9] = '\0'

scanf() of string will automatically put '\0' at the end. When you are printing using %s, your printf() method will print until it reaches '\0'. But if in the array there is no '\0' character, then it may crash or print garbage value form system dump, because the printf() will try to print beyond your array indexing.