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
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++.