Inex
Inex

Reputation: 602

code do not read text from file c++

Microsoft Visual Studio 2017 C++

Problem is that code do not read text that is in the file MVS point by red wave test.txt and in dialog box is written: argument of type "const char" is incompatible with parameter of type char

File is in the project folder////

//

#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 words

Problem.

problem

Upvotes: 0

Views: 306

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57678

One of the issues of your program is that your function take a pointer to Mutable, R/W character array:

void HowManyWords(char Filename[]);

In the main function, you are passing it a const char string. Text literals are constant.

If you are not changing the contents of Filename, pass it as "read-only":

void HowManyWords(char const * Filename)

Reading the type from right to left, this is a pointer to constant ("read only") char. The function is stating that it will not change the contents of Filename. Thus you can pass it a string literal.

For more information, search the internet for "c++ const correctness pointers".

Edit 1: simple example
Here is a simple working example showing the correct parameter syntax for your HowManyWords function:

#include <stdio.h>

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

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

Here is the compilation and output, using g++ on Cygwin, on Windows 7:

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

$ ./main.exe
Filename:
test.txt





$

As I stated above, comment out your code in HowManyWords and get the parameter passing working correctly. Next, add a little bit of code; compile, test and repeat.

Upvotes: 1

Related Questions