I have read a text file to console and printed the file after reading,

int textLength=0
int c;

int c;
                FILE *file;
                file = fopen("ModestProposal.txt", "r");
                if (file) 
                {
                    while ((c = getc(file)) != EOF)
                    putchar(c);
                    //fclose(file);
                }
                    textLength = strlen(c);//get the length of the text

How come I can not strlen "c" ? aren't they both int? I'm getting a warning error saying argument of type "int" is incompatible with the perimeter of type const char. Any way to grab the text from the text file as a whole int ?

strlen takes a character pointer as its parameter.

size_t strlen(const char *s)

You're using strlen() incorrectly. It doesn't take an int, it takes a const char*.

The way you have your code written, it might be easier to simply count, one by one, how many characters there are by counting them as you print them, using textLength as a counter.

if(file)
{
    while((c = getc(file)) != EOF)
    {
        textLength++;
        putchar(c);
    }
}

The code seems too much C style to me. why couldnt you just use a proper CPP style. And could even make it 3 lines once you get the idea.

 ifstream file("text.txt"); //open file
    string stuff,cc;
    if(file.is_open()){ // check file if success
        while(!file.eof()){
          file >> stuff;  // put line date here
         cc +=stuff;   //append data
          } 
          cout <<cc.length(); // use the length method
    }
    else
    {
        cout <<"error"; // error checking
        }

  file.close(); //house keeping

You can read the entire data using geline. Then use gcount() function to give you char numner inside the file.

 i

The reason why i need to do what I am doing is because I need to do a max check on how many characters are allowed, like this and do something with it.

The above code works for counting all characters but I need to append it or convert the whole string to a integer after counting the characters because my "textLength" is of integer value.

if(textLength < TEXTMAX)//did not reach the maximum text limit, OK
    {
        fflush(stdin);
        for(i=0;i<=textLength;i++)//traverse each character in the string
    {

So if i read the file as a string using getline method, how would I convert the string to const char to compare max text limit?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.