how do you read a text file into c++ program?

the text file has both text (for the first line) and integers (for other lines) and is space delimited.
Try this link ;-)

http://www.cplusplus.com/doc/tutorial/files/

Hope that helps...
oh, i forgot to add that all the data in the second file is suppose to be separate, not in one line then the rest in one line (which would be the integers)
So you're basically asking how to convert a String to an integer??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    using namespace std;
    string s = "1234";
    stringstream ss(s); // Could of course also have done ss("1234") directly.
    int i;
    if ((ss >> i).fail()) {
         //error
     }
     cout<<i<<endl;
     return 0;
}


You could also use boost lexical cast which would be the cleanest solution IMHO...

Hope that helps ;-)
Or maybe I just don't get your question :-/... Could you reformulate please...
no... i guess i'll be more specific on the type of program i'm trying to create
see there's a file with the seven days of the week (this is the first line...comma delimited)
then there are seven lines with integers also comma delimited because it's more than one set of data (each line will go to one of the days of the week)
what i want to know is how do i input both text and integers from the data so that I can separate each line into one of the days of the week
this is what the text file looks like:

monday tuesday wednesday thursday friday saturday sunday
3422 2352 5454 3411 9845 3432 8452 3453 3422
3421 2453 7845 3992 3753 2134 8574 4274 2834
3422 8593 2452 4757 3452 7583 2342 8457 2342
2342 8577 3444 2830 2353 3423 1200 8475 3423
1123 4855 3488 7573 1342 3453 8894 1248 4829
4857 7359 4747 3684 5702 4799 2847 5382 8899
8909 8790 2312 3489 7878 3290 1388 4792 9088


and this is what i want the program to look like:

monday
3422
2352
5454
3411
9845
3432
8452
3453
3422

tuesday
3421
2453
7845
3992
3753
2134
8574
4274
2834

etc....

thanks for your suggestions so far, i've learned a lot (:
Last edited on
Glad to help :-)

You can work with splitting the strings....
Read every line on it's own...
Then on the first line (3422 2352 ...) you split the strings by ' ' (whitespace)

Splitting a string is pretty straight forward... You can work with find() and substr(int from, int to)

You can find more info here:
http://www.linuxselfhelp.com/HOWTO/C++Programming-HOWTO-7.html

Hope that helps ;-)
Topic archived. No new replies allowed.