2

私のコードの問題は何ですか?

#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 ==========
4

2 に答える 2

8

明らかに、これをC++ではなくCとしてコンパイルしています。VSはC99をサポートしていません。その場合、これを行うことはできません。

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

代わりにこれを行う必要があります:

int i;

...

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

i関数内のすべてのステートメントの前にの宣言が必要な場合。

于 2013-03-07T00:29:57.507 に答える
2

オリ・チャールズワースがあなたに必要な答えを与えてくれたと思います。

ここにあなたのためのいくつかのヒントがあります:

  • 文字列内で円記号を使用する場合は、2つの円記号を配置する必要があります。

  • の結果を確認する必要がfopen()あり、そうであるNULL場合はエラーで停止する必要があります。

  • 文字列の配列のサイズを指定しないでください。コンパイラに、割り当てる文字数をカウントさせます。

  • ループではfor、文字列のサイズをハードコーディングしないでください。を使用sizeof()してコンパイラに長さをチェックさせるか、終了するヌルバイトが表示されるまでループします。後者をお勧めします。

書き直されたバージョン:

#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;
}
于 2013-03-07T00:43:35.880 に答える