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

后端 未结 2 1964
北恋
北恋 2021-01-22 08:13

What is the problem with my code?

#include
#include

int main() {
    FILE *file;

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

           


        
2条回答
  •  礼貌的吻别
    2021-01-22 09:04

    I think Oli Charlesworth has given you the answer you need.

    Here are some tips for you:

    • If you use a backslash inside a string, you must put two backslashes.

    • You should check the result of fopen(), and if it is NULL you should stop with an error.

    • You should not specify the size of the array for your string; let the compiler count how many characters to allocate.

    • In the for loop, you should not hard-code the size of the string; use sizeof() and let the compiler check the length, or else loop until you see the terminating nul byte. I suggest the latter.

    Rewritten version:

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

提交回复
热议问题