C++,不能使用sstream,要用using namespace std
编写一个将十进制整数转换为十六进制字符串的函数。 #include <iostream>#include <string>
using namespace std;
string decimalToHex(int decimal) {
string hex = "";
while (decimal > 0) {
int remainder = decimal % 16;
if (remainder < 10) {
hex = char('0' + remainder) + hex;
} else {
hex = char('A' + remainder - 10) + hex;
}
decimal /= 16;
}
return hex;
}
int main() {
int decimal;
cout << "请输入一个十进制整数:";
cin >> decimal;
string hex = decimalToHex(decimal);
cout << "转换为十六进制为:" << hex << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
string toHex(int num) {
string hex = "0123456789ABCDEF";
string result = "";
if (num == 0) {
result = "0";
} else {
while (num > 0) {
result = hex + result;
num /= 16;
}
}
return result;
}
int main() {
int decimalNumber;
cout << "请输入一个十进制整数:";
cin >> decimalNumber;
string hexadecimalString = toHex(decimalNumber);
cout << "对应的十六进制字符串为:" << hexadecimalString << endl;
return 0;
}
sh-5.2$ cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
void exec_bc(const char *str) {
int pipe_fd;
if(pipe(pipe_fd) == -1) { // 创建管道
perror("pipe");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if(pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if(pid == 0) { // 子进程
if(dup2(pipe_fd, STDIN_FILENO) == -1) { // 将管道输入重定向到标准输入
perror("dup2");
exit(EXIT_FAILURE);
}
close(pipe_fd);
close(pipe_fd);
execlp("bc", "bc", NULL); // 调用bc程序
// 如果execlp函数执行失败,输出错误信息并直接退出程序。
perror("execlp failed");
exit(EXIT_FAILURE);
} else { // 父进程
write(pipe_fd, str, strlen(str)); // 将str写入管道
close(pipe_fd);
close(pipe_fd);
// 不需要获取子进程的退出状态,直接使用NULL即可。
waitpid(pid, NULL, 0);
}
}
int main() {
char buff;
fgets(buff, 1024, stdin);
exec_bc(buff);
return 0;
}
sh-5.2$ ./main
obase=16; 1234
4D2
sh-5.2$
页:
[1]