【问题标题】:Read input Space Separated from the File读取与文件分离的输入空间
【发布时间】:2016-06-26 14:55:23
【问题描述】:

我必须使用 C++ 编写一个程序,该程序必须从 .txt 文件中读取数据,其中数据是这种形式

DATE TIME DATETIME(Unix time_T 值)MachineID 温度
现在必须取 time_T 值和温度,我需要执行基数排序 这个文件有超过 3,00,000 条记录,每行保存 1 条记录,如上所述,我知道基数排序,但我完全不知道将上述字符串格式拆分为单独的队列(time_T,Temp)。我正在使用以下代码读取文件:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

int main() {
    ifstream input("demo.txt");
    string line;    
    while (getline(input, line)) {
        cout << line << '\n';
    }
    return 0;    
}

更新 输入示例 2016-01-01 00:00:04.039251 1451624404 01948 4.9

【问题讨论】:

  • std::istringstream, operator&gt;&gt;
  • 请通过在互联网上搜索“stackoverflow c++ 读取空间分隔”来找到您的重复项。另请参阅相关的“stackoverflow c++ 读取文件 csv”,其中“csv”表示逗号分隔值。
  • 当询问如何解析输入文件时,请显示输入格式的示例(如果需要,还显示架构)。
  • @RaviMehta 正如@LogicStuff 提到的,istringstream 会很好用。看到这个答案:stackoverflow.com/a/7868998/2951830

标签: c++ queue radix-sort


【解决方案1】:

无需在迭代中使用两次inFile。我认为这应该会有所帮助:

int main() {
    ifstream inFile("filename.txt");
    int i = 0;

string date,time,datetime;

time_t t1;
float temprature;

while (inFile >> date >> time >> datetime >> t1>> temprature)
{
    cout << t1 << " " << temprature << endl;
}
inFile.close();
return 0;
}

【讨论】:

    【解决方案2】:

    试试这个...

    int main() {
    ifstream inFile("filename.txt");
    std::string line;
    int i = 0;
    
    string date,time,datetime;
    
    time_t t1;
    float temprature;
    
    while (std::getline(inFile, line))
    {
        inFile >> date >> time >> datetime >> t1>> temprature;
        cout << t1 << " " << temprature<<endl;
    }
    inFile.close();
    return 0;
    }
    

    【讨论】:

    • 这将丢弃所有奇数行,因为getline 读取了一行,然后inFile &gt;&gt; 也读取了一行,但只使用了第二行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 2012-05-03
    • 2011-11-30
    • 2012-10-17
    • 2023-04-04
    相关资源
    最近更新 更多