繁体   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