gpt4 book ai didi

c++ - 将文本文件读入C++

转载 作者:行者123 更新时间:2023-11-28 07:51:13 25 4
gpt4 key购买 nike

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?

最佳答案

file_name >> input 的默认行为是类型安全的,因此 file_name 字节偏移量指针永远不会针对 Time(1)8:56 这样的输入递增: 18。您可以使用 string input; 而不是 double input; 来检索值,然后您可以使用以下标准 c 库检查它们的类型。

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

Here是文档。

关于c++ - 将文本文件读入C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13736499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com