Adding words into string array from file C++ -
basically i'm doing reading words file, taking letters out of it, putting them array , counting how many have. problem way i've written it, when there 2 non-letters next each other word created. should change here?
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string str[10000]; string temp = ""; char c; int = 0, count = 0; //open file fstream sample; sample.open("sample.txt"); while (!sample.eof()){ sample.get(c); //convert character lowercase , append temp. string if ((c>=65 && c<=90) || (c>=97 && c<=122)){ c = tolower(c); temp += c; } //when word ends, add array , add 1 word count else if (c<65 || (c>90 && c<97) || c>122){ str[i] = temp; count++; i++; temp = ""; } } sample.close(); cout << "the number of words found in file " << count << endl; return 0; }
first of all, if can, please avoid using raw arrays in c++ outside of classes can control lifetime of array via destructors etc. considered practice this. instead use container classes provided standard library (like vector, array, ...).
second can use stringstream's words out of file more easily.
third please refrain using namespace std;. considered bad practice.
slightly better example problem of getting strings:
#include <iostream> #include <sstream> #include <fstream> #include <vector> #include <string> int main() { std::vector<std::string> str; // open file std::ifstream sample("sample.txt"); std::stringstream strm; strm << sample.rdbuf(); while(strm) { std::string word; strm >> word; if (word.empty()) continue; str.push_back(word); } std::cout << "word count: " << str.size() << std::endl; }
i hope can adapt rest of problem easily.
Comments
Post a Comment