int main()
{
ifstream infile; //Container for the file
infile.open("nameOfTheFile.txt"); //Name of the file you want to open
string stringFromFile; //string variables to store extracted strings
if(infile.fail()) //Display error if the file failed to open
{
cout<<"Input file failed to open";
}
else
{
getline(infile, stringFromFile);
}
cout<<stringFromFile
i am slightly confused with the text file to i researched it and it can up with this.
-----------------------------------------------------------------------------------------
#define CHUNK 1024 /* read 1024 bytes at a time */
char buf[CHUNK];
FILE *file;
size_t nread;
file = fopen("test.txt", "r");
if (file) {
while ((nread = fread(buf, 1, sizeof buf, file)) > 0)
fwrite(buf, 1, nread, stdout);
if (ferror(file)) {
/* deal with error */
}
fclose(file);
}
----------------------------------------------------------------------------------------------------
method above is essentially how you will read a file with a dynamically allocated array
//Don't forget to display error if the input file does not open, as I did on my first comment
//so you would know what's happening if if doesn't display anything on the command //prompt.
int main()
{
ifstream infile;
infile.open("listOfWords.txt"); //open file
for(string listOfWords; getline(infile, listOfWords, '.'); ) //read sentences including
//spaces
cout<<listOfWords; //Display sentences
return 0;
}
I hope this helps ! MiiNiPaa how do you do those progamming text ?
It depends what tool you're using to create the c++ code, if you're using MS Visual Studio then you should use the StreamWriter and StreamReader classes:
1 2 3 4 5 6 7 8 9 10 11 12
// Creating a stream reader object and assigning the "hello.txt" text file to it
StreamReader readText = new StreamReader("hello.txt");
// Assigning the value in the text file to a string variable using the ReadLine() function
string helloText = readText.ReadLine();
// Creating a new stream writer object and assigning the "hello.txt" text file to it
StreamWriter editText = new StreamWriter("hello.txt");
// Using the WriteLine() function to add the text "hello everybody" to the original text file
editText.WriteLine("hello everybody");
You should have the System.IO namespace if you want to use the StreamWriter and StreamReader functions (which you may already have). If you're just using pure C++ then use the iostream functions described in the comments above.