#include <iostream>
using namespace std;
int main() {
string x;
cin >> x;
char ch;
/* how can i remove the last comma? */
int l = x.length();
for (int i = 0; i < l; i ) {
ch = x.at(i);
cout << ch << ",";}
return 0;
}
我期望:輸入:1234 輸出:1,2,3,4 但現在:輸入:1234 輸出:1,2,3,4,
uj5u.com熱心網友回復:
只需列印第一個字符,然后列印所有其他以逗號開頭的元素。你當然需要處理空字串的特殊情況:
if (!x.empty())
{
std::cout << x[0];
for (auto pos = x.begin() 1; pos != x.end(); pos)
{
std::cout << ',' << *pos;
}
}
std::cout << '\n';
uj5u.com熱心網友回復:
這樣做(基本上你在檢查它是否是最后一次迭代并且適用于任何數字之間單獨列印逗號):
#include <iostream>
using namespace std;
int main() {
string x;
cin >> x;
char ch;
/* how can i remove the last comma? */
int l = x.length();
for (int i = 0; i < l; i ) {
ch = x.at(i);
cout << ch ;
if (i==l-1) {break;}
cout << ",";}
return 0;
}
uj5u.com熱心網友回復:
只是一個有趣的 C 視圖解決方案 :)
#include <iostream>
#include <string>
#include <ranges>
int main()
{
std::string input("1,2,3,4,5,");
for(const auto c : input |
std::views::reverse | // start looking from back of string
std::views::drop_while([](const char c) { return c == ','; }) | // drop all characters from the start that are commas
std::views::reverse // then look over the reverse of the reverse.
)
{
std::cout << c;
}
return 0;
}
uj5u.com熱心網友回復:
但更符合您的原始代碼。并且不使用“使用命名空間 std”,而是使用基于范圍的 for 回圈。現場演示:https ://onlinegdb.com/7WmSDm9Do
#include <iostream>
int main()
{
std::string x{"12345"};
//std::cin >> x;
bool print_a_comma{false};
for(const auto c : x )
{
// adjusted logic, only print a comma before next output if needed
if ( print_a_comma ) std::cout << ", ";
std::cout << c;
print_a_comma = true;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/511336.html
標籤:C
