Can anyone help me to write a simple sample code about to read the file line by line and store it into cstring? The file contains few rows of sentences.THANK YOU!
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<char*> text; // for holding all text lines
std::ifstream ifs( "myTextFile.txt");
if(!ifs) {
std::cerr << "Text-file couldn't opened!\n";
return 1;
}
// We reading a whole line to an std::string and then we copy
// each character into a c-string
while (true) {
std::string line;
std::getline( ifs, line);
if (!ifs) break; // Input file is at end or an error happened.
char * tmp = newchar[line.length()+1];
for (int i = 0; i < line.length(); ++i)
{
tmp[i] = line[i];
}
tmp[line.length()] = '\0';
text.push_back( tmp);
}
// for testing:
for( char* & line : text) { std::cout << line << '\n'; }
// free memory on heap:
for ( char* & line : text) { delete line; }
}
/*
// The same program without using c-strings:
int main()
{
std::vector<std::string> text; // this container holds all lines.
std::ifstream ifs( "myTextFile.txt");
if(!ifs) { std::cerr << "Text file couldn't opened!\n"; return 1; }
std::string line;
while ( std::getline( ifs, line)) {
text.push_back( line );
}
// for testing:
for (auto & line : text) std::cout << line << '\n';
// We don't need to free any memory from heap manually.
}
*/
I think yes because my problem is like I need to read every sentence in textfile using getline.
Go through every character in the sentence....something like that. The code I wrote will store all the characters in every sentences into the cstring...i can't solve it
This is clearly a homework assignment, and OP is asking us to do it for him.
@wandou99
Do you not have course notes or anything? Do you have specific constraints in this assignment. You have only given one very general piece of information: “The file contains a few rows of sentences.” How many is “a few”? Three? Five? Less than fifteen?
Are you storing every line in a different C-string? Or can you reuse one C-string over and over? Surely you aren’t referring to Embarcadero’s CString class, but to char* strings, right?
Is this supposed to be using C++? Or C? Because the way you do it is significantly different between the two, with different extra care needed when you have got it.