0

I am trying to read text in a file and store it in a string so that it can be output and read

although when I try to see the output string it seems to have a completely different output. does anyone know why and what I can do to fix it?

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <string>
#pragma warning(disable:4996)
using namespace std;

int main()
{
    char str=' ';
    string myString = "";
    
    FILE* filepointer = fopen("C:/Users/user/Desktop/textfile.txt", "r");
    if (filepointer == NULL) {
        printf("Can't open file\n");
    }
    else {

        while (!feof(filepointer)) {
            str=fgetc(filepointer);
            printf("%c",str);
           
            myString = myString + str;
         

        }
        fclose(filepointer);
        printf("\n\rmyString = %s ", myString);
    }
}

to be clear the content in the file is t te tes test testi testin testing

this is the code output

1 Answer 1

0

you are trying to printf an std::string.

This doesn't work, because, since printf is a c function, it doesn't know about c++ strings.

You could use std::cout << myString << std::endl Or use the c_str() member function of myString to convert it to an c-style string.

printf("\n\rmyString = %s ", myString.c_str());

While the compiler accepts it just fine, it is usually things like this that makes people tell you not to mix c and c++.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.