簡體   English   中英

我如何只將該行的特定部分讀入結構?

[英]How do I only read a certain part of this line into a structure?

我正在使用以逗號(,)作為分隔符的csv文件。 csv文件的文本文件版本中的特定行如下所示。

Station Name,MONTREAL/PIERRE ELLIOTT TRUDEAU INTL,,,,,,,,,,,,,,,,,,,,,,,

我希望只能存儲“ MONT / L / PIERRE ELLIOTT TRUDEAU INTL”,減去引號。 因此,我希望不能存儲STATION NAME。 根據我的研究,我的代碼如下所示。

#include<string>
#include<sstream>
#include<fstream>
using namespace std;

struct company_data
{
    string station_name, province, climate_identifier, TC_identifier, time_info;
    float latitude, longitude;
    int WMO_identifier;
    string E, M, NA, symbol;
};

void accept_company_data (company_data initial)
{
    ifstream infile;
    infile.open("eng-hourly-montreal-wind_dec_2015.csv");
    string line, temp1,temp2;
    getline (infile, line);
    istringstream iss(line);
    iss>>temp1;
    iss>>initial.station_name;
    cout<<initial.station_name;
}

任何幫助將不勝感激。

有兩種解決方法

這兩個都使用“ C”字符串。 您可以使用string.c_str()來實現。

  1. 看一下strtok()-這將基於某些定界符(在您的情況下為逗號)將字符串分解。 在Linux / UNIX上鍵入'man strtok'

  2. 將指針設置為字符串的開頭並循環,直到您按下逗號為止。 然后將指針增加一個(以越過逗號)並保存該位置(為其設置一個指針)。 現在繼續尋找下一個逗號。 下一個逗號時,您可以將所有字符從開始指針復制到結束指針。

例如:

char *string = "you're input,with commas, in it";
char *start_pointer, *end_pointer, *ptr;

ptr = string;   
while (*ptr!=',') ptr++; // scan along looking for comma
ptr++;  // the above while, will have stopped on the comma
start_pointer=ptr;  
while (*ptr!=',' && *ptr) ptr++;
end_pointer=ptr;

//now you can copy to your destination
char destination_buffer[128];  
char *des=destination_buffer;
for(ptr=start_pointer;ptr<end_pointer;) *des++=*ptr++; 

上面的方法效率不高,因為您掃描了兩次之后發現了可以做的第一個逗號即可

while(*ptr!=','&&*ptr) *des++=*ptr++; 

“ && * ptr”正在尋找一個分隔字符串結尾的NULL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM