Quote:Original post by bluefox25
I want to store each individual word into a variable but it isnt working
*** Source Snippet Removed ***
I'd say Character I/O is the hardest thing I have encountered in my class, even arrays and pointers were not as hrd to undeerstand
}
Not quite. First of all, you haven't declared a variable "str" anywhere.
But more to the point, std::getline stores a single line in a single string.
From there, we can parse it more.
Instead of the arbitrary limit of 100 strings in a line (which in most places will be far too much, but if it is ever too little then you'll be in trouble) we will use another std::container. I see you are already using std::string so you will be familiar with how they "just work" when it comes to sizes, they grow big enough anything you try fit in them. We have the equivalent for arrays in the form of std::vector. We can simply push_back something into the vector to add something. We can ask the std::vector how many elements it has, so we can iterator over it (or we could use iterators, but Ill try keep it as simple as possible):
#include <vector>#include <string>#include <fstream>// other includes// this example will read all the lines from the file// and print them all.int main() { std::vector<std::string> lines; std::ifstream readFile("story.txt"); std::string currentLine; while( std::getline(readFile,currentLine) ) { lines.push_back(currentLine); } // now in between here we might do something interesting. for( int i = 0; i < lines.size() ; ++i ) { std::cout << lines << '\n'; }}
Now we come to parsing the individual lines. The Standard C++ Library includes a class called std::stringstream. Its like a std::fstream, or std::cout/std::cin. But it works in memory, nothing need be printed or sent to a file. Also we can read and write to it. So we can throw in an string, and read it out a int.
Example:
// attempts to read the first item in the// string as an integerint intFromString( const std::string & input ) { std::stringstream stream; stream << input; int value; stream >> value; return value;}
This is a simple way to do string/integer conversions if you don't have boost.
It is used like so:
std::stringstream stream;// a string with a string, int and float as an example:stream << "jimmy 7 3.14";std::string name;int age;float pi;stream >> name >> age >> pi;std::cout << "Person with name: " << name << " age: " << age << " and who thinks pi is " << pi << '\n';
Now, our needs are actually simpler. We have a bunch of words in a line.
We need to separate into a bunch of identical objects. We can store them in a std::vector instance to aid us.
std::vector<std::string> parse( const std::string &line ){ std::vector<std::string> words; std::stringstream stream; stream << line; std::string currentWord; while( stream >> currentWord ) { words.push_back(currentWord); } return words;}
I hope you'll be able to build on this to do whatever you are trying.