[英]How to input a string or integer to a C++ program from the command line?
我想从命令行读取输入,如果它是 integer,请将其连同其十六进制格式一起写入文件,如果用户输入“end”,则循环应终止。
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
void numToFile() {
int i;
std::string input;
std::ofstream ofs;
ofs.open("outputFile.txt", std::ios::out | std::ios::trunc);
while (input != "end") {
std::cin >> input;
ofs << input << " = 0x" << std::ios::hex << input << std::endl;
}
ofs.close();
}
int main() {
numToFile();
}
但是,在 output 文件中,我找到了这个 output:
12 = 0x204812
34 = 0x204834
49 = 0x204849
end = 0x2048end
不太确定如何将输入定向到字符串或 integer 以转换为十六进制格式。
编辑:
Including `stoi`:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <iomanip>
void numToFile() {
int i;
std::string input;
std::ofstream ofs;
ofs.open("outputFile.txt", std::ios::out | std::ios::trunc);
while (input != "end") {
std::cin >> input;
ofs << std::setw(5) << std::setfill('0');
// NOT: std::ios::hex !?
ofs << input << " = 0x" << std::hex << std::stoi(input) << std::endl;
}
ofs.close();
}
您需要尽快检查输入是否有效。
void numToFile() {
int i;
std::string input;
std::ofstream ofs;
ofs.open("outputFile.txt", std::ios::out | std::ios::trunc);
while (std::cin>>input) {
if(input == "end") break;
ofs << std::setw(5) << std::setfill('0');
// NOT: std::ios::hex !?
ofs << input << " = 0x" << std::hex << std::stoi(input) << std::endl;
}
ofs.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.