代码不从文件中读取文本 C++

code do not read text from file c++

微软 Visual Studio 2017 C++

问题是代码不读取文件 MVS 中红色波浪指向的文本 test.txt 并在对话框中写入:"const char" 类型的参数与 char 类型的参数不兼容

文件在项目文件夹中////

//

#include "stdafx.h"
#include "stdlib.h"
# include <fstream>
#include <stdio.h>


void HowManyWords(char FileName[]) {
  FILE*file = fopen(FileName, "rt");
//if (!file)return false;
int count = 0;
char str[100];
while (fgets(str, 100, file)) {
    for (int i = 0; str[i]; i++) {

        if (str[i] >= 'A'&&str[i] <= 'Z' || str[i] >= 'a'&&str[i] <= 'z') {
            if (str[i + 1] >= 'A'&&str[i + 1] <= 'Z' || str[i + 1] >= 'a'&&str[i + 1] <= 'z') {
            }
            else {
                count++;
            }
        }
    }
    printf("%s", str);
}
fclose(file);
printf("%i", count);
}

int main()
 {
HowManyWords("test.txt");

printf("\n");
system("pause");
return 0;
}

//111个字

问题。

你的程序的一个问题是你的函数接受了一个指向 Mutable,R/W 字符数组的指针:

void HowManyWords(char Filename[]);

main 函数中,您向它传递了一个 const 字符字符串。文本文字是常量。

如果您不更改 Filename 的内容,请将其作为 "read-only":

传递
void HowManyWords(char const * Filename)

从右到左读取类型,这是一个指向常量("read only")的指针char。该函数声明它不会更改 Filename 的内容。因此,您可以将字符串文字传递给它。

有关详细信息,请在互联网上搜索 "c++ const correctness pointers"。

编辑 1:简单示例
这是一个简单的工作示例,显示了 HowManyWords 函数的正确参数语法:

#include <stdio.h>

void HowManyWords(const char Filename[])
{
    puts("Filename: ");
    puts(Filename);
    puts("\n");
}

int main()
{
    HowManyWords("test.txt");
    puts("\n");
    return 0;
}

这是编译和输出,在 Cygwin 上使用 g++,在 Windows 7 上:

$ g++ -o main.exe main.cpp

$ ./main.exe
Filename:
test.txt





$

如上所述,在 HowManyWords 中注释掉您的代码并使参数传递正常工作。接下来,添加一点代码;编译、测试和重复。