简体   繁体   English

将文本文件读入C ++

[英]Reading text file into C++

I was writing a program which could read inputs directly from a text file into a C++ file. 我正在编写一个程序,该程序可以将输入直接从文本文件读取到C ++文件中。 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. 但是,当我执行程序时,我陷入了无限循环,而我看到的只是在屏幕上写的0。 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 . file_name >> input的默认行为是安全类型,因此对于诸如Time(1)8:56:18类的输入,file_name字节偏移指针永远不会递增。 You may use string input; 您可以使用string input; instead of double input; 而不是double input; to retrieve the values, then later you may check their types by using following standard c library. 检索值,然后您可以使用以下标准c库检查它们的类型。

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

Here is the documentation. 是文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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