2015-03-08 45 views
0

我有一個.txt文件,其中包含我需要處理的數千行浮點值。我不知道每個特定行有多少個值。我想將所有的值存儲在一個數組中。讀取特定行中的值(可變數值)並將它們存儲在數組中

這一切到目前爲止我有:

string line; 
int row = 0; 
ifstream file_input (input.c_str()); 
while (getline(file_input, line)) 
{ 
    row++; 
    if (row == 8) // if I want to read the 8th line 
    { 
     cout << line; 
    } 
} 

此代碼打印8號線,這是一個大量的數值完全的所有內容。我想將所有這些值存儲到一個數組中。 我該怎麼做?

回答

2

您可以使用std::stringstream(或std::istringstream)從行中讀取這些float並將它們推送到std::vector

std::vector<float> vec; 
std::string line; 
std::ifstream file_input (input); 
int row = 0; 
while (getline(file_input, line)) 
{ 
    ++row; 

    if (row == 8) // if I want to read the 8th line 
    { 
     cout << line; 

     std::istringstream iss(line); 
     float value; // auxiliary variable to which you extract float from stringstream 

     while(iss >> value)  // yields true if extraction succeeded 
      vec.push_back(value); // and pushes value into the vector 

     break; 
    } 
} 

或者參見this post以獲得更專業的方法。

0

既然你已經採取了線的文件轉換成字符串,就可以將字符串轉換爲的焦炭一個向量,並作出的char *點這個載體,通過的char *成以下函數作爲第一個參數:

char * strtok(char * str,const char * delimiters);

你的情況的第二個參數是一個空格「」。接收到的字符指針可以轉換爲浮點數,每個標記可以存儲在一個數組中!

int nums(char sentence[ ]) //function to find the number of words in a line 
    { 
    int counted = 0; // result 

    // state: 
    const char* it = sentence; 
    int inword = 0; 

    do switch(*it) { 
     case '\0': 
     case ' ': case '\t': case '\n': case '\r': 
      if (inword) { inword = 0; counted++; } 
      break; 
     default: inword = 1; 
    } while(*it++); 

    return counted; 
} 

int main() 
{ 
ifstream file_input (input.c_str()); 
int row=0; 
while (getline(file_input, abc)) 
{ 

vector<char> writable(abc.begin(), abc.end()); 
vector<char> buf(abc.begin(), abc.end()); 

writable.push_back('\0'); 
buf.push_back('\0'); 

char *line=&writable[0]; 

char *safe=&buf[0]; 


char* s= "123.00"; 

     float array[100]; 
     char *p; 
     int i=0; 

     p= strtok (line, " "); 
     array[i]=atof(p); 
     cout<<" "<<array[i]; 

     i++; 
     while (i<nums(safe)) 
      { 
       p = strtok (NULL, " "); //returns a pointer to the token 
       array[i]=atof(p); 
       cout<<" "<<array[i]; 
       i++; 
      } 
    return 0; 
} 

不幸循環:(!p值= NULL)不工作並導致段故障,所以我不得不使用另一種載體預先計算在該行的字的數量因爲strtok()將字符串修改爲char *

相關問題