So lets say i have a program and a file, 'Program' and 'stuff.txt'. stuff.txt conatins the following.
NAME: "John Doe"
AGE: 12
GENDER: IceCream
....blah blah and so on.
How would i have my program to view this file and when its see's NAME it creates a new string called NAME and then in that stores in that string "John Doe" and then goes onto the second line recogonizes the word AGE creates a int then stores the age in that int. How will i be able to do this and have the program read this file like that and then store that data.
I would use getline to read each line into a string. Then I would parse that string to see if it contained "NAME:". if it does, I would assign the string that follows "NAME:" In your input to another string name "Name". if it doesn't match "NAME:", I would then check to see if it matched "AGE:", and so forth.
#include <string>
#include <iostream>
#include <sstream>
int main(int argc, char** arv)
{
// initialize input stream with data
std::istringstream ins("this is a text ");
// load words to this container
std::string out;
// read the words until some data in the input stream
while (ins >> out)
{
std::cout << out << std::endl;
}
return 0;
}
So i got the getline to stop at the ':' symbol and store NAME into a variable but then how would i be able to get the actual value to another variable?
As coder777 has already pointed out, splitting strings on spaces is better done using operator>> instead of getline with a ' ' delimiter. To start with, there's no need to ignore empty strings, as you don't get any.
And it's better to use
14 15 16
while (getline(ins, out, ' '))
{
// etc
than
14 15 16 17
while (ins.good())
{
getline(ins, out, ' ');
// etc
(in parallel with the way coder777 is using operator>> above.)
operator>> also deals with other whitespace chars while the article's first example does not.