簡體   English   中英

視覺工作室表達抱怨失蹤';' 輸入c程序后

[英]visual studio express complains missing ';' after type in c program

我的代碼有什么問題?

#include<stdio.h>
#include<string.h>

int main() {
    FILE *file;

    char string[32] = "Teste de solução";

    file = fopen("C:\file.txt", "w");

    printf("Digite um texto para gravar no arquivo: ");
    for(int i = 0; i < 32; i++) {
        putc(string[i], file);
    }

    fclose(file);

    return 0;
}

錯誤:

c:\users\guilherme\documents\visual studio 2010\projects\helloworld\helloworld\hello.c(13): error C2143: syntax error : missing ';' before 'type'
1>c:\users\guilherme\documents\visual studio 2010\projects\helloworld\helloworld\hello.c(13): error C2143: syntax error : missing ';' before 'type'
1>c:\users\guilherme\documents\visual studio 2010\projects\helloworld\helloworld\hello.c(13): error C2143: syntax error : missing ')' before 'type'
1>c:\users\guilherme\documents\visual studio 2010\projects\helloworld\helloworld\hello.c(13): error C2143: syntax error : missing ';' before 'type'
1>c:\users\guilherme\documents\visual studio 2010\projects\helloworld\helloworld\hello.c(13): error C2065: 'i' : undeclared identifier
1>c:\users\guilherme\documents\visual studio 2010\projects\helloworld\helloworld\hello.c(13): warning C4552: '<' : operator has no effect; expected operator with side-effect
1>c:\users\guilherme\documents\visual studio 2010\projects\helloworld\helloworld\hello.c(13): error C2065: 'i' : undeclared identifier
1>c:\users\guilherme\documents\visual studio 2010\projects\helloworld\helloworld\hello.c(13): error C2059: syntax error : ')'
1>c:\users\guilherme\documents\visual studio 2010\projects\helloworld\helloworld\hello.c(13): error C2143: syntax error : missing ';' before '{'
1>c:\users\guilherme\documents\visual studio 2010\projects\helloworld\helloworld\hello.c(14): error C2065: 'i' : undeclared identifier
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

顯然你將它編譯為C,而不是C ++。 VS不支持C99,在這種情況下你可能不會這樣做:

for (int i = 0; i < 32; i++)

你需要這樣做:

int i;

...

for(i = 0; i < 32; i++)

如果i的聲明必須在函數中的所有聲明之前。

我認為Oli Charlesworth已經為您提供了所需的答案。

以下是一些提示:

  • 如果在字符串中使用反斜杠,則必須放置兩個反斜杠。

  • 您應該檢查fopen()的結果,如果它是NULL您應該停止並顯示錯誤。

  • 您不應該為字符串指定數組的大小; 讓編譯器計算要分配的字符數。

  • for循環中,你不應該硬編碼字符串的大小; 使用sizeof()並讓編譯器檢查長度,否則循環直到看到終止的nul字節。 我建議后者。

改寫版:

#include<stdio.h>
#include<string.h>

int main() {
    FILE *file;
    int i;

    char string[] = "Teste de solução";

    file = fopen("C:\\tmp\\file.txt", "w");
    if (!file) {
        printf("error!\n");
    }

    printf("Digite um texto para gravar no arquivo: ");
    for(i = 0; string[i] != '\0'; i++) {
        putc(string[i], file);
    }

    fclose(file);

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM