【问题标题】:using getline to get multiple lines from a file and input them in different arrays使用 getline 从文件中获取多行并将它们输入到不同的数组中
【发布时间】:2014-03-20 05:58:56
【问题描述】:

我正在尝试从文件流中做一个简单的getline,然后将不同的输入存储到不同的数组中。

输入文件是这样的。

销售时间、价格 ($)、数量、价值 ($)、条件 2013 年 10 月 10 日 04:57:27 PM,5.81,5000,29050.00,LT XT 10/10/2013 04:48:05 下午,5.81,62728,364449.68,SX XT 10/10/2013 04:10:33 PM,.00,0,.00,

请注意,前两行是多余的,应该忽略。所有数据都应存储在各自的数组中,例如 time[i]、price[i]。

string datefield;
int count = 0;
string date[5000];
float pricefield;
float price [5000];
int volume[5000];
float value[5000];
string condition[5000];
int i = 0;

while (!infile.eof()) {
    count++;
    getline(infile,datefield);
    while (count >= 2) {
        getline(infile,date[i], ',');
        infile  >> price[i] >> volume[i];
        i++;
        break;
    }
}

这里的问题是,volume[i]. 没有输入

【问题讨论】:

标签: c++ arrays getline


【解决方案1】:
  1. 不要将eof() 放在while 条件中。这是不对的!签出:Why is iostream::eof inside a loop condition considered wrong?。为了锻炼,你可以改变

    while (!infile.eof()) {
        count++;
        getline(infile,datefield);
        ... 
    

    while (getline(infile,datefield)) {
        count++;
        ... 
    
  2. 在数据读取步骤中您应该非常小心。对于",.00,0,.00,",由于其中没有空格,因此>> price[i] >> volume[i] 将尝试将所有这些内容读取到price[i]。不会将任何内容读入volume[i]。要解决这个问题,您可以先将此部分读取到string,然后通过拆分从中读取数据。或者将','全部替换为空格,然后放到一个std::istringstream中,就可以正确使用>> price[i] >> volume[i]了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2019-09-28
    相关资源
    最近更新 更多