2014-11-13 178 views
0

我们今天在课堂上做了这个练习,但不幸的是,我的代码没有正常运行。它不会打印string1。我的老师也搞不明白为什么会发生这种情况。打印字符串的问题

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

void main() 
{ 
char string1[20]; 
char string2[] = "It is almost end of semester!"; 
size_t idx; 
int size; 

printf("Enter string1:\n"); 
scanf_s("%s", string1); 
size = sizeof(string2)/sizeof(char); 
printf("\nString 1 is : %s\n\n", string1); 
for (idx = 0; idx < size; idx++) 
{ 
    printf("%c ", string2[idx]); 
} 
puts(""); 
system("pause");; 
} 
+1

在'system(“pause”)末尾有2个分号;' – nbro

+2

'scanf_s',那是什么? – nbro

+0

@波利,这并没有改变任何东西。 – Novaea

回答

1

scanf_s需要额外的参数。

scanf_s("%s", string1, _countof(string1)); 
0

您已经使用scanf_s代替scanf,正如林奇先生正确地指出需要一个额外的参数。你可以用scanf本身完成同样的事情。一种方法是如下:

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

int main() { 
    char string1[20]; 
    char string2[] = "It is almost end of semester!"; 
    size_t idx; 
    int size; 

    printf ("Enter string1:\n"); 
    scanf ("%[^\n]%*c", string1); 
    string[19] = 0;       /* force null-termination of string1 */ 
    size = sizeof (string2)/sizeof (char); 
    printf ("\nString 1 is : %s\n\n", string1); 
    for (idx = 0; idx < size; idx++) { 
     printf ("%c ", string2[idx]); 
    } 
    puts (""); 
    return 0; 
} 

输出:

$ ./bin/strprn 
Enter string1: 
scanf_s is not scanf 

String 1 is : scanf_s is not scanf 

I t i s a l m o s t e n d o f s e m e s t e r ! 

注:main()是类型intvoid无论让你得到什么毫秒逃脱。它也返回一个值。

+0

我使用'scanf_s',因为scanf是“不安全的”,并引发一个警告,不会让我运行该程序。 – Novaea

+0

咦? 'scanf'是C标准的一部分,不是不安全的,并且会让你运行你的程序。只需复制并粘贴我发布和查看的内容即可。 –

+0

VS 2014发出警告。我必须禁用警告才能使用scanf。 – Novaea