i need to write a program in c++ that is going to read English sentences from a textfile, a line at a time and store them in an array. the file has 100 sentences each occupying a single line.
reading from a textfile into an array
Collapse
X
-
Originally posted by sajeniai need to write a program in c++ that is going to read English sentences from a textfile, a line at a time and store them in an array. the file has 100 sentences each occupying a single line. -
Originally posted by arneAnd what is it you have difficulties with?
i have managed to have the program read from a textfile but it is not storing into an array. displaying the senteces has to be from an array not from the textfile as it is doing.Comment
-
Originally posted by sajeniahaving problems with array declaration. is it suppossed to be a one-dim array or a two-dim array?
i have managed to have the program read from a textfile but it is not storing into an array. displaying the senteces has to be from an array not from the textfile as it is doing.
Code:vector<strings> sentences;
Comment
-
Originally posted by sajeniai don't even understand this line of code that u've sent. can u elaborate. what is a vector anyway?
For example,
Code:vector<string> vec_of_str; vector<int> vec_of_int; vector<double> vec_of_dbl;
BTW, string is also a type from the STL and no built-in type like int or float.
Please refer also to http://www.cppreference.com to get an idea what things you can do with vectors and strings.
Here comes the code that may do what you need. Have a look and try to understand it (I added some comments :))
Code:#include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; int main( void ) { // define an infile stream ifstream fin( "textfile.txt" ); // define a vector of strings vector<string> sentences; //define a temporary string string tmp_str; // read the file line by line into tmp_str while( getline( fin, tmp_str ) ) { // append the tmp_str as a new last // element to sentences sentences.push_back( tmp_str ); } // print out the 3rd element of our vector cout << sentences[2]; return 0; }
Comment
Comment