2014-01-21 28 views
-1

串在我如何篩選出整數一組向量C++

std::vector<string> x; 
std::cout << "Please enter in values "; 
std::getline(std::cin, numbers); 
numbers.push_back(x) 

比方說,用戶輸入
3.9823米/秒34.0公里/ | S22米/秒

我想知道如何才能夠只抓住字符串中的數字並忽略這些單位? 我想要的值3.9823,34.0和222

+0

我認爲你應該使用結構{float數; UNIT單位; };枚舉UNIT {m = 0,km,}。並創建struct的向量。 – CreativeMind

+0

@Kara你應該把一個更好的標題。 – sashoalm

回答

1

簡單的解決方法

std::vector<string> x {"3.9823 m/s", "34.0 km/s", "222 m/s"}; 

for (int i=0; i<x.size(); i++) 
{ 
    stringstream ss(x[i]); 

    float t; 
    ss >> t; 

    cout << static_cast<int>(t) << endl; 
} 

輸出

3 
34 
222 
+0

什麼是汽車?我是C++編程新手 – Kara

+0

'auto'是C++ 11中的一個新關鍵字,用於支持基於範圍的循環。無論如何,我通過索引基礎循環重寫代碼。 – deepmax

0

好了,就處理輸入這樣的健壯性沒有評論,你的問題太自我不一致來回答,但給你一個想法:

std::vector<double> results; 
double n; 
for (int i = 0; i < 3 && std::cin >> n; ++i) 
{ 
    results.push_back(n); 
    std::string units; 
    std::cin >> units; 
} 
0

這是一種方法; (使用strtofstrtol如果你從字面上想只有整數

#include <iostream> 
#include <vector> 
#include <cstdlib> // strtof() 

int main(){ 
    std::vector<std::string> x; 
    x.push_back("3.9823 m/s"); 
    x.push_back("34.0 km/s"); 
    x.push_back("222 m/s"); 
    char *pEnd; 

    float numbers[x.size()]; 

    for(int i = 0; i<x.size(); ++i){ 
     numbers[i] = strtof(x[i].c_str(), &pEnd); 
    } 

    for(int i = 0; i<x.size(); ++i){ 
     std::cout<< numbers[i] << '\n'; 
    } 

} 

輸出;

3.9823 
34 
222 
0

在一般情況下,你可以使用std::stringstream錯誤檢查:

#include <iostream> 
#include <sstream> 
#include <vector> 
#include <string> 

int main() 
{ 
    std::string line; 
    std::cout << "Please enter in values "; 
    std::getline(std::cin, line); 

    std::stringstream is(line); 
    std::vector<double> x; 
    double temp; 

    while (1) { 
     is >> temp; 
     while (!is.eof() && (is.bad() || is.fail())) { 
      is.clear();   // clear the error flag. 
      is.ignore(256, ' '); // ignore upto space. 
      is >> temp;   // try to read again. 
     } 
     if (is.eof()) { 
      break; 
     } 
     x.push_back(temp); 
    } 

    for (int i = 0; i < x.size(); i++) 
     std::cout << x[i] << " "; 
    return 0; 
} 
+0

幾乎在那裏,但這不會處理中間的單位,不是? – legends2k

+0

@ legends2k注意確定,會檢查。 –

+0

@ legends2k是的你是對的,提取錯誤檢查必須完成。更新了代碼。 –