2014-11-13 89 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