How to swap two digits in int number in C++

2 Answers

0 votes
#include <iostream>  
#include <sstream>  

int main() {  
    int n = 840192;  
    
    std::cout << n << "\n";  
    
    std::stringstream ss;  
    ss << n;  
    
    std::string s;  
    ss >> s;  
    
    char tmp = s[0];
    s[0] = s[3];
    s[3] = tmp;
    
    std::stringstream ss1(s);  

    ss1 >> n;
      
    std::cout << n;  
    
    return 0;
}  




/*
run:

840192
140892

*/

 



answered Jan 14, 2021 by avibootz
0 votes
#include <iostream>  
#include <sstream>  

int main() {  
    int n = 840192;  
    
    std::cout << n << "\n";  
    
    std::stringstream ss;  
    ss << n;  
    
    std::string s;  
    ss >> s;  
    
    char tmp = s[0];
    s[0] = s[3];
    s[3] = tmp;
    
    std::stringstream().swap(ss);
    ss << s;
    
    ss >> n;
      
    std::cout << n;  
    
    return 0;
}  




/*
run:

840192
140892

*/

 



answered Jan 14, 2021 by avibootz

Related questions

1 answer 139 views
1 answer 169 views
1 answer 171 views
1 answer 170 views
1 answer 175 views
175 views asked Dec 1, 2020 by avibootz
1 answer 164 views
2 answers 224 views
...