簡體   English   中英

從文件讀取數字到字符串再到數組

[英]Reading numbers from file to string to array

我正在從文件中讀取數字,說:

1 2 3 4 5

我想將這些數據從文件中讀取到字符串中,再放入數組中以進行進一步處理。 這是我所做的:

float *ar = nullptr;
while (getline(inFile, line))
{
    ar = new float[line.length()];
    for (unsigned int i = 0; i < line.length(); i++)
    {
          stringstream ss(line);
          ss >> ar[i];
    }
}
unsigned int arsize = sizeof(ar) / sizeof(ar[0]);
delete ar;

可以說它僅在文件中獲取第一個值的范圍內起作用。 如何獲得要輸入所有值的數組? 我調試了程序,可以確認該行具有所有必需的值; 但float數組沒有。 請幫忙,謝謝!

line.length()是該行中的字符數,而不是單詞/數字/任何數字。

使用可以輕松調整大小的向量,而不是嘗試弄亂指針。

std::vector<float> ar;
std::stringstream ss(line);
float value;
while (ss >> value) {     // or (inFile >> value) if you don't care about lines
    ar.push_back(value);
}

該大小現在可以作為ar.size() 您不能使用sizeof ,因為ar是一個指針,而不是數組。

最簡單的選擇是使用標准庫及其流。

$ cat test.data
1.2 2.4 3 4 5

給定文件后,您可以像這樣使用流庫:

#include <fstream>
#include <vector>
#include <iostream>

int main(int argc, char *argv[]) {
  std::ifstream file("./test.data", std::ios::in);

  std::vector<float> res(std::istream_iterator<float>(file),
                         (std::istream_iterator<float>()));

  // and print it to the standard out
  std::copy(std::begin(res), std::end(res),
            std::ostream_iterator<float>(std::cout, "\n"));

  return 0;
}

當我想逐行從文件中提取數據以填充我想使用的sql數據庫時,我遇到了這個問題。 有許多解決此特定問題的方法,例如:

解決方案是使用帶while語句的stringstream將帶有while語句的文件中的數據放入數組中

//編輯

  1. 使用getline的While語句

//此解決方案不是很復雜,並且非常易於使用。

新改進的簡單解決方案:

#include <iostream>
#include <fstream>   
#include <string>
#include <vector>
using namespace std;

int main()
{       
    ifstream line;
    line.open("__FILENAME__");
    string s;
    vector<string> lines;
    while(getline(line, s)) 
    {
        lines.push_back(s);
    }
    for(int i = 0;i < lines.size();i++)
    {
        cout << lines[i] << " ";
    }
    return 0;
}

編譯后的代碼進行檢查-http://ideone.com/kBX45a

atof呢?

std::string value = "1.5";
auto converted = atof ( value.c_str() );

比較完整:

while ( std::getline ( string ) ) 
{
   std::vector < std::string > splitted;
   boost::split ( splitted, line, boost::is_any_of ( " " ) );

   std::vector < double > values;       
   for ( auto const& str: splitted ) {
      auto value = atof ( str.c_str() );
      values.push_back ( value );
   }
}

暫無
暫無

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

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