次のコード行があります。
vector<string> c;
string a;
for(int i=0;i<4;i++){
cin>>a;
c.push_back(a);
}
入力を次のように提供した場合:
120$、132$、435$、534$
整数値を個別に抽出し、それらを合計して合計値を取得するにはどうすればよいですか?
次のコード行があります。
vector<string> c;
string a;
for(int i=0;i<4;i++){
cin>>a;
c.push_back(a);
}
入力を次のように提供した場合:
120$、132$、435$、534$
整数値を個別に抽出し、それらを合計して合計値を取得するにはどうすればよいですか?
たとえばstd::getline
、カンマを使用してカスタムの「行」セパレーターを使用し、文字列から最後の文字を取り除き ( ) 、整数に変換するために'$'
使用できます。std::stoi
std::vector<int> c;
for (int i = 0; i < 4; i++)
{
std::string a;
std::getline(std::cin, a, ',');
a = a.substr(a.length() - 1); // Remove trailing dollar sign
c.push_back(std::stoi(a));
}
編集:使用std::accumulate
:
int sum = std::accumulate(c.begin(), c.end(), 0);
編集2:std::strtol
代わりに使用std::stoi
:
この関数std::stoi
は最新の C++ 標準 (C++11) で新しく追加されたもので、まだすべての標準ライブラリでサポートされているわけではありません。次に、古い C 関数を使用できますstrtol
。
c.push_back(int(std::strtol(a.c_str(), 0, 10)));
正規表現とストリームを使用できます:
#include <regex>
#include <iostream>
#include <sstream>
const std::string Input("120$,132$,435$,534$");
int main(int argc, char **argv)
{
const std::regex r("[0-9]+");
int Result = 0;
for (std::sregex_iterator N(Input.begin(), Input.end(), r); N != std::sregex_iterator(); ++N)
{
std::stringstream SS(*N->begin());
int Current = 0;
SS >> Current;
Result += Current;
std::cout << Current << '\n';
}
std::cout << "Sum = " << Result;
return 0;
}
出力:
120
132
435
534
Sum = 1221
数値の後に a が続くことを確認する必要がある場合は'$'
、正規表現を次"[0-9]+\\$"
のように変更します。この部分は、数値変換stringstream
の末尾を無視します。'$'
#include <regex>
#include <iostream>
#include <sstream>
const std::string Input("120$,132$,435$,534$,1,2,3");
int main(int argc, char **argv)
{
const std::regex r("[0-9]+\\$");
int Result = 0;
for (std::sregex_iterator N(Input.begin(), Input.end(), r); N != std::sregex_iterator(); ++N)
{
std::stringstream SS(*N->begin());
int Current = 0;
SS >> Current;
Result += Current;
std::cout << Current << '\n';
}
std::cout << "Sum = " << Result;
return 0;
}
出力:
120
132
435
534
Sum = 1221
入力が大きすぎない場合 (特に 1 行の場合)、最も簡単な解決策は、すべてを文字列にパックし、それを解析して、std::istringstream
各数値フィールドを変換する を作成することです (またはboost::lexical_cast<>
、偶然にも、適切なセマンティクスを持っています (通常、文字列を組み込みの数値型に変換する場合)。ただし、この単純なものについては、ストリームから直接読み取ることができます。
std::istream&
ignoreDollar( std::istream& stream )
{
if ( stream.peek() == '$' ) {
stream.get();
}
return stream;
}
std::istream&
checkSeparator( std::istream& stream )
{
if ( stream.peek() == ',' ) {
stream.get();
} else {
stream.setstate( std::ios_base::failbit );
}
return stream;
}
std::vector<int> values;
int value;
while ( std::cin >> value ) {
values.push_back( value );
std::cin >> ignoreDollar >> checkSeparator;
}
int sum = std::accumulate( values.begin(), values.end(), 0 );
(この特定のケースでは、すべてをループ内で実行する方が簡単な場合がありwhile
ます。ただし、マニピュレータは一般的に有用な手法であり、より広いコンテキストで使用できます。)
簡単なバージョン:
int getIntValue(const std::string& data)
{
stringstream ss(data);
int i=0;
ss >> i;
return i;
}
int getSum(std::vector<std::string>& c)
{
int sum = 0;
for (auto m = c.begin(); m!= c.end(); ++m)
{
sum += getIntValue(*m);
}
return sum;
}
終わり