c读写字符串visual studio 2013

时间:2015-06-14 14:36:52

标签: c arrays visual-studio-2013 c-strings

每次我运行它都会在我输入字符串时停止工作。我使用visual studio 2013.Here'我的代码:

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

3 个答案:

答案 0 :(得分:1)

可能发生的是stdout输出缓冲区未刷新。默认情况下stdout 行缓冲意味着写入stdout的输出实际上不会输出,直到有换行符。

所以解决方案只是写一个换行符:

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

另请注意,您不能写入超过九个字符的输入,或者您将超出数组x的边界并且具有undefined behavior。数字9来自你的数组是10 char大,C中的字符串需要一个额外的字符来终止字符串,所以你可以放在x中的最大字符串是10减1。

答案 1 :(得分:0)

试试这个:

#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);
}

答案 2 :(得分:0)

如果您将{9}以上的字符放入x,那么您的程序将提供未定义的行为。假设您输入abcdefghi,则x的实际内容如下:

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()字符串会自动将'\0'放在最后。使用%s进行打印时,您的printf()方法会一直打印到'\0'。但是如果在数组中没有'\0'字符,那么它可能会崩溃或打印垃圾值表系统转储,因为printf()将尝试打印超出您的数组索引。

相关问题