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
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
好了,就處理輸入這樣的健壯性沒有評論,你的問題太自我不一致來回答,但給你一個想法:
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;
}
這是一種方法; (使用strtof或strtol如果你從字面上想只有整數)
#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
在一般情況下,你可以使用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;
}
幾乎在那裏,但這不會處理中間的單位,不是? – legends2k
@ legends2k注意確定,會檢查。 –
@ legends2k是的你是對的,提取錯誤檢查必須完成。更新了代碼。 –
我認爲你應該使用結構{float數; UNIT單位; };枚舉UNIT {m = 0,km,}。並創建struct的向量。 – CreativeMind
@Kara你應該把一個更好的標題。 – sashoalm