简体   繁体   中英

Reading text file into C++

I was writing a program which could read inputs directly from a text file into a C++ file. However, the contents of the file come in different formats, for example time. The input file looks like this:

Time(1) Price(1)
8:56:18 1250.00
9:00:25 1250.25
9:21:36 1250.50
9:23:32 1249.75

Time(2)
8:55:28
9:02:14
9:20:23
9:21:37
Price(2)
1680.50
1681.00
1680.50
1681.50

My program to read the file is as follows:

int main()
{
    string file;
    cout << "Enter a file name to read input: ";
    cin >> file;

    ifstream file_name(file.c_str());

    while(!file_name.eof())
    {
        double input;
        file_name >> input;
        cout << input << endl;
    }
}

But when I executed the program, I get stuck in an infinite loop and all I see are 0s written on the screen. Is this being caused due the formatting of the time?

The default behavior of file_name >> input is type safe therefore file_name byte offset pointer never increments for inputs like Time(1) or 8:56:18 . You may use string input; instead of double input; to retrieve the values, then later you may check their types by using following standard c library.

#include <cstdlib>
.
.
.
atof()
atoi()
.

Here is the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM