| re: how to do a simple loop to store strings ??
news.hku.hk wrote:[color=blue]
> is there any way to make a loop to store strings??
>
> e.g. abc.txt contains 3 lines i.e.
> this is line 1.
> this is line 2.
> this is line 3.
>
> i want to create a loop that can make the three strings contains the
> corresponding lines,
>
> string line1; //contains "this is line1."
> string line2; // contains "this is line2."
> string line3; // contains "this is line3."
> int no_of_lines = 3;
>
> can a simple for loop do this ??[/color]
Sure!
#include <sstream>
#include <string>
using namespace std;
string int_to_str(int i) {
ostringstream o;
o << i;
return o.str();
}
int main() {
const int no_of_lines=3;
string lines[no_of_lines];
for(unsigned int i=0;i<no_of_lines;++i)
lines[i]="this is line"+int_to_str(i);
}
.... except that you now have lines[0],lines[1],lines[2]
instead of line1, line2,line3.
HTH,
- J.
PS. What you really need is a textbook. |