我有一個字串向量,其中如果第一個字符是“1”,那么我需要將整數(表示為字串)推送到一個向量中,否則我只需要列印第一個字符。使用 stringstream 時,以下是我撰寫的代碼。
vector<string> arr = {"1 23", "2", "1 45", "3", "4"};
vector<int> v;
for(string x : arr){
stringstream ss(x);
string word;
string arr[2];
int i =0 ;
while(ss >> word){
arr[i ] = word;
}
i = 0;
if(arr[0] == "1")
v.push_back(atoi(arr[1]));
else
cout << arr[0] << endl;
除了使用陣列 arr,有沒有辦法在第一個單詞為“1”時從 stringstream 中獲取下一個單詞?因為當我嘗試 stringstream 時,從頭開始重新開始。
uj5u.com熱心網友回復:
該代碼使用std::stringstream,但它沒有利用此物件的任何優勢,例如直接提取int.
std::vector<std::string> arr = {"1 23", "2", "1 45", "3", "4"};
std::vector<int> v;
for ( auto const& word : arr )
{
std::stringstream ss{ word }; // Initialize with a string,
int first;
if ( ss >> first )
{ // ^^^^^^^^^^^ but extract an int...
if ( first == 1 )
{
int second;
if ( ss >> second ) // and another.
v.push_back(second);
}
else
std::cout << first << '\n';
} // Error handling is left to the reader.
}
uj5u.com熱心網友回復:
假設字串總是格式良好并采用您描述的格式,并且字串中的數字始終是有效整數,您可以改為這樣:
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
const vector<string> arr = {"1 23", "2", "1 45", "3", "4"};
vector<int> v;
for (const string& s : arr) {
if (s.size() > 2 && s[0] == '1' && s[1] == ' ') {
v.push_back(atoi(s.c_str() 2));
} else {
cout << s << "\n";
}
}
for (const int i: v) {
cout << i << "\n";
}
}
對于陣列中不以 1 開頭的字串和您說應該列印的空格,我只是列印了整個字串而不是它的第一個字符。
如果您不確定陣列中的字串,則需要先檢查錯誤。另外,請參閱如何將 std::string 轉換為 int?對于 atoi() 的替代品。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388745.html
上一篇:從生成的字串掃描
下一篇:Python字串格式的區別
