Microsoft Visual Studio 2017 C ++
问题是代码不会通过red wave test.txt读取文件MVS点中的文本,并且在对话框中写入:类型" 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字
问题。
答案 0 :(得分:0)
你的程序的一个问题是你的函数指向Mutable,R / W字符数组:
void HowManyWords(char Filename[]);
在main
函数中,您传递的是 const 字符串。文字文字是不变的。
如果您不更改Filename
的内容,请将其作为“只读”传递:
void HowManyWords(char const * Filename)
从右到左读取类型,这是一个指向常量(“只读”)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;
}
以下是在Windows 7上使用Cygwin上的g++
编译和输出:
$ g++ -o main.exe main.cpp
$ ./main.exe
Filename:
test.txt
$
如上所述,请在HowManyWords
中注释掉您的代码,并使参数传递正常工作。接下来,添加一些代码;编译,测试和重复。