簡體   English   中英

將文件讀取到由逗號和換行符分隔的向量中

[英]Reading File into Vector Delimited by Comma and New Line

假設我要讀取.txt文件並以這種方式設置格式

Max,1979
Wade,1935
Hugh,1983
Eric,1936

這是我正在使用的代碼

  1. 讀入文件。
  2. 將其存儲到string和int的向量中(分別用於名稱和年份)

     void calcAges(){ while (getline(infile, line, ',')){ names.push_back(line); years.push_back(line); } } void printNames(){ cout << "\\n\\tDisplaying data...\\n"; for (int i = 0; i < counter; i++){ cout << (i + 1) << ".\\tName: " << names[i] << "\\tYear: " << years[i] << endl; } } 

輸出應如下所示:

1.    Name: Max    Year: 1979
.
.
.
and so on...

但是,我在嘗試創建它時遇到了麻煩,因此我讀入“ infile”的文件以逗號和換行符分隔。 我將這些變量存儲到向量數組中,以便稍后進行排序和切換。 在這一點上,我很沮喪。

給定','作為分隔符后,新行將被視為普通字符。 因此,請使用getline()而不指定分隔符(默認為換行符),然后嘗試從獲取的字符串中提取名稱和年份。 使用find_first_of()substr()可以很容易地完成它

例:

while(getline(infile,str))
{
     int index = str.find_first_of(',');
     string name = str.substr(0,index);
     string date = str.substr(index+1);
      // Do something with name and date

}

當涉及到此類操作時, StringStream的功能要強大得多。 但是,在您的情況下(這被認為很簡單),您可以通過對字符串的簡單操作來擺脫困境。 我建議將每一行讀入您的臨時字符串,然后在逗號上將其分割,然后將值添加到向量中,如下所示:

void calcAges(){
    while (getline(infile, line)){  // Read a whole line (until it reads a '\n', by default)
        names.push_back(line.substr(0,line.find(",")); // Read from the beginning of the string to the comma, then push it into the vector
        years.push_back(std::stoi(line.substr(line.find(",") + 1)); // Read from the comma to the end of the string, parse it into an integer, then push it into the vector
    }
}

我假設您正在使用<string>庫中的std::string作為line變量的類型。

我並沒有進行編譯和測試,所以我不確定它是否可以正常工作,但是我寫它只是為了讓您對邏輯方法有所了解

干杯

暫無
暫無

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

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